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 |
---|---|---|---|---|---|---|
ColBERT | ColBERT-master/colbert/modeling/tokenization/doc_tokenization.py | import torch
from transformers import BertTokenizerFast
from colbert.modeling.tokenization.utils import _split_into_batches, _sort_by_length
class DocTokenizer():
def __init__(self, doc_maxlen):
self.tok = BertTokenizerFast.from_pretrained('bert-base-uncased')
self.doc_maxlen = doc_maxlen
self.D_marker_token, self.D_marker_token_id = '[D]', self.tok.convert_tokens_to_ids('[unused1]')
self.cls_token, self.cls_token_id = self.tok.cls_token, self.tok.cls_token_id
self.sep_token, self.sep_token_id = self.tok.sep_token, self.tok.sep_token_id
assert self.D_marker_token_id == 2
def tokenize(self, batch_text, add_special_tokens=False):
assert type(batch_text) in [list, tuple], (type(batch_text))
tokens = [self.tok.tokenize(x, add_special_tokens=False) for x in batch_text]
if not add_special_tokens:
return tokens
prefix, suffix = [self.cls_token, self.D_marker_token], [self.sep_token]
tokens = [prefix + lst + suffix for lst in tokens]
return tokens
def encode(self, batch_text, add_special_tokens=False):
assert type(batch_text) in [list, tuple], (type(batch_text))
ids = self.tok(batch_text, add_special_tokens=False)['input_ids']
if not add_special_tokens:
return ids
prefix, suffix = [self.cls_token_id, self.D_marker_token_id], [self.sep_token_id]
ids = [prefix + lst + suffix for lst in ids]
return ids
def tensorize(self, batch_text, bsize=None):
assert type(batch_text) in [list, tuple], (type(batch_text))
# add placehold for the [D] marker
batch_text = ['. ' + x for x in batch_text]
obj = self.tok(batch_text, padding='longest', truncation='longest_first',
return_tensors='pt', max_length=self.doc_maxlen)
ids, mask = obj['input_ids'], obj['attention_mask']
# postprocess for the [D] marker
ids[:, 1] = self.D_marker_token_id
if bsize:
ids, mask, reverse_indices = _sort_by_length(ids, mask, bsize)
batches = _split_into_batches(ids, mask, bsize)
return batches, reverse_indices
return ids, mask
| 2,248 | 34.140625 | 104 | py |
ColBERT | ColBERT-master/colbert/modeling/tokenization/query_tokenization.py | import torch
from transformers import BertTokenizerFast
from colbert.modeling.tokenization.utils import _split_into_batches
class QueryTokenizer():
def __init__(self, query_maxlen):
self.tok = BertTokenizerFast.from_pretrained('bert-base-uncased')
self.query_maxlen = query_maxlen
self.Q_marker_token, self.Q_marker_token_id = '[Q]', self.tok.convert_tokens_to_ids('[unused0]')
self.cls_token, self.cls_token_id = self.tok.cls_token, self.tok.cls_token_id
self.sep_token, self.sep_token_id = self.tok.sep_token, self.tok.sep_token_id
self.mask_token, self.mask_token_id = self.tok.mask_token, self.tok.mask_token_id
assert self.Q_marker_token_id == 1 and self.mask_token_id == 103
def tokenize(self, batch_text, add_special_tokens=False):
assert type(batch_text) in [list, tuple], (type(batch_text))
tokens = [self.tok.tokenize(x, add_special_tokens=False) for x in batch_text]
if not add_special_tokens:
return tokens
prefix, suffix = [self.cls_token, self.Q_marker_token], [self.sep_token]
tokens = [prefix + lst + suffix + [self.mask_token] * (self.query_maxlen - (len(lst)+3)) for lst in tokens]
return tokens
def encode(self, batch_text, add_special_tokens=False):
assert type(batch_text) in [list, tuple], (type(batch_text))
ids = self.tok(batch_text, add_special_tokens=False)['input_ids']
if not add_special_tokens:
return ids
prefix, suffix = [self.cls_token_id, self.Q_marker_token_id], [self.sep_token_id]
ids = [prefix + lst + suffix + [self.mask_token_id] * (self.query_maxlen - (len(lst)+3)) for lst in ids]
return ids
def tensorize(self, batch_text, bsize=None):
assert type(batch_text) in [list, tuple], (type(batch_text))
# add placehold for the [Q] marker
batch_text = ['. ' + x for x in batch_text]
obj = self.tok(batch_text, padding='max_length', truncation=True,
return_tensors='pt', max_length=self.query_maxlen)
ids, mask = obj['input_ids'], obj['attention_mask']
# postprocess for the [Q] marker and the [MASK] augmentation
ids[:, 1] = self.Q_marker_token_id
ids[ids == 0] = self.mask_token_id
if bsize:
batches = _split_into_batches(ids, mask, bsize)
return batches
return ids, mask
| 2,449 | 36.692308 | 115 | py |
ColBERT | ColBERT-master/colbert/modeling/tokenization/utils.py | import torch
def tensorize_triples(query_tokenizer, doc_tokenizer, queries, positives, negatives, bsize):
assert len(queries) == len(positives) == len(negatives)
assert bsize is None or len(queries) % bsize == 0
N = len(queries)
Q_ids, Q_mask = query_tokenizer.tensorize(queries)
D_ids, D_mask = doc_tokenizer.tensorize(positives + negatives)
D_ids, D_mask = D_ids.view(2, N, -1), D_mask.view(2, N, -1)
# Compute max among {length of i^th positive, length of i^th negative} for i \in N
maxlens = D_mask.sum(-1).max(0).values
# Sort by maxlens
indices = maxlens.sort().indices
Q_ids, Q_mask = Q_ids[indices], Q_mask[indices]
D_ids, D_mask = D_ids[:, indices], D_mask[:, indices]
(positive_ids, negative_ids), (positive_mask, negative_mask) = D_ids, D_mask
query_batches = _split_into_batches(Q_ids, Q_mask, bsize)
positive_batches = _split_into_batches(positive_ids, positive_mask, bsize)
negative_batches = _split_into_batches(negative_ids, negative_mask, bsize)
batches = []
for (q_ids, q_mask), (p_ids, p_mask), (n_ids, n_mask) in zip(query_batches, positive_batches, negative_batches):
Q = (torch.cat((q_ids, q_ids)), torch.cat((q_mask, q_mask)))
D = (torch.cat((p_ids, n_ids)), torch.cat((p_mask, n_mask)))
batches.append((Q, D))
return batches
def _sort_by_length(ids, mask, bsize):
if ids.size(0) <= bsize:
return ids, mask, torch.arange(ids.size(0))
indices = mask.sum(-1).sort().indices
reverse_indices = indices.sort().indices
return ids[indices], mask[indices], reverse_indices
def _split_into_batches(ids, mask, bsize):
batches = []
for offset in range(0, ids.size(0), bsize):
batches.append((ids[offset:offset+bsize], mask[offset:offset+bsize]))
return batches
| 1,833 | 34.269231 | 116 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tools/test.py | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import os
import mmcv
import torch
from mmcv import Config, DictAction
from mmcv.parallel import MMDataParallel
from mmcv.runner import get_dist_info, init_dist, load_checkpoint
from mmedit.apis import multi_gpu_test, set_random_seed, single_gpu_test
from mmedit.core.distributed_wrapper import DistributedDataParallelWrapper
from mmedit.datasets import build_dataloader, build_dataset
from mmedit.models import build_model
from mmedit.utils import setup_multi_processes
def parse_args():
parser = argparse.ArgumentParser(description='mmediting tester')
parser.add_argument('config', help='test config file path')
parser.add_argument('checkpoint', help='checkpoint file')
parser.add_argument('--seed', type=int, default=None, help='random seed')
parser.add_argument(
'--deterministic',
action='store_true',
help='whether to set deterministic options for CUDNN backend.')
parser.add_argument('--out', help='output result pickle file')
parser.add_argument(
'--gpu-collect',
action='store_true',
help='whether to use gpu to collect results')
parser.add_argument(
'--save-path',
default=None,
type=str,
help='path to store images and if not given, will not save image')
parser.add_argument('--tmpdir', help='tmp dir for writing some results')
parser.add_argument(
'--cfg-options',
nargs='+',
action=DictAction,
help='override some settings in the used config, the key-value pair '
'in xxx=yyy format will be merged into config file. If the value to '
'be overwritten is a list, it should be like key="[a,b]" or key=a,b '
'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" '
'Note that the quotation marks are necessary and that no white space '
'is allowed.')
parser.add_argument(
'--launcher',
choices=['none', 'pytorch', 'slurm', 'mpi'],
default='none',
help='job launcher')
parser.add_argument('--local_rank', type=int, default=0)
args = parser.parse_args()
if 'LOCAL_RANK' not in os.environ:
os.environ['LOCAL_RANK'] = str(args.local_rank)
return args
def main():
args = parse_args()
cfg = Config.fromfile(args.config)
if args.cfg_options is not None:
cfg.merge_from_dict(args.cfg_options)
# set multi-process settings
setup_multi_processes(cfg)
# set cudnn_benchmark
if cfg.get('cudnn_benchmark', False):
torch.backends.cudnn.benchmark = True
cfg.model.pretrained = None
# init distributed env first, since logger depends on the dist info.
if args.launcher == 'none':
distributed = False
else:
distributed = True
init_dist(args.launcher, **cfg.dist_params)
rank, _ = get_dist_info()
# set random seeds
if args.seed is not None:
if rank == 0:
print('set random seed to', args.seed)
set_random_seed(args.seed, deterministic=args.deterministic)
# build the dataloader
# TODO: support multiple images per gpu (only minor changes are needed)
dataset = build_dataset(cfg.data.test)
loader_cfg = {
**dict((k, cfg.data[k]) for k in ['workers_per_gpu'] if k in cfg.data),
**dict(
samples_per_gpu=1,
drop_last=False,
shuffle=False,
dist=distributed),
**cfg.data.get('test_dataloader', {})
}
data_loader = build_dataloader(dataset, **loader_cfg)
# build the model and load checkpoint
model = build_model(cfg.model, train_cfg=None, test_cfg=cfg.test_cfg)
args.save_image = args.save_path is not None
empty_cache = cfg.get('empty_cache', False)
if not distributed:
_ = load_checkpoint(model, args.checkpoint, map_location='cpu')
model = MMDataParallel(model, device_ids=[0])
outputs = single_gpu_test(
model,
data_loader,
save_path=args.save_path,
save_image=args.save_image)
else:
find_unused_parameters = cfg.get('find_unused_parameters', False)
model = DistributedDataParallelWrapper(
model,
device_ids=[torch.cuda.current_device()],
broadcast_buffers=False,
find_unused_parameters=find_unused_parameters)
device_id = torch.cuda.current_device()
_ = load_checkpoint(
model,
args.checkpoint,
map_location=lambda storage, loc: storage.cuda(device_id))
outputs = multi_gpu_test(
model,
data_loader,
args.tmpdir,
args.gpu_collect,
save_path=args.save_path,
save_image=args.save_image,
empty_cache=empty_cache)
if rank == 0 and 'eval_result' in outputs[0]:
print('')
# print metrics
stats = dataset.evaluate(outputs)
for stat in stats:
print('Eval-{}: {}'.format(stat, stats[stat]))
# save result pickle
if args.out:
print('writing results to {}'.format(args.out))
mmcv.dump(outputs, args.out)
if __name__ == '__main__':
main()
| 5,285 | 32.66879 | 79 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tools/onnx2tensorrt.py | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import os
import os.path as osp
import warnings
from typing import Iterable, Optional
import cv2
import mmcv
import numpy as np
import onnxruntime as ort
import torch
from mmcv.ops import get_onnxruntime_op_path
from mmcv.tensorrt import (TRTWrapper, is_tensorrt_plugin_loaded, onnx2trt,
save_trt_engine)
from mmedit.datasets.pipelines import Compose
def get_GiB(x: int):
"""return x GiB."""
return x * (1 << 30)
def _prepare_input_img(model_type: str,
img_path: str,
config: dict,
rescale_shape: Optional[Iterable] = None) -> dict:
"""Prepare the input image
Args:
model_type (str): which kind of model config belong to, \
one of ['inpainting', 'mattor', 'restorer', 'synthesizer'].
img_path (str): image path to show or verify.
config (dict): MMCV config, determined by the inpupt config file.
rescale_shape (Optional[Iterable]): to rescale the shape of the \
input tensor.
Returns:
dict: {'imgs': imgs, 'img_metas': img_metas}
"""
# remove alpha from test_pipeline
model_type = model_type
if model_type == 'mattor':
keys_to_remove = ['alpha', 'ori_alpha']
elif model_type == 'restorer':
keys_to_remove = ['gt', 'gt_path']
for key in keys_to_remove:
for pipeline in list(config.test_pipeline):
if 'key' in pipeline and key == pipeline['key']:
config.test_pipeline.remove(pipeline)
if 'keys' in pipeline and key in pipeline['keys']:
pipeline['keys'].remove(key)
if len(pipeline['keys']) == 0:
config.test_pipeline.remove(pipeline)
if 'meta_keys' in pipeline and key in pipeline['meta_keys']:
pipeline['meta_keys'].remove(key)
# build the data pipeline
test_pipeline = Compose(config.test_pipeline)
# prepare data
if model_type == 'mattor':
raise RuntimeError('Invalid model_type!', model_type)
if model_type == 'restorer':
data = dict(lq_path=img_path)
data = test_pipeline(data)
if model_type == 'restorer':
imgs = data['lq']
else:
imgs = data['img']
img_metas = [data['meta']]
if rescale_shape is not None:
for img_meta in img_metas:
img_meta['ori_shape'] = tuple(rescale_shape) + (3, )
mm_inputs = {'imgs': imgs, 'img_metas': img_metas}
return mm_inputs
def onnx2tensorrt(onnx_file: str,
trt_file: str,
config: dict,
input_config: dict,
model_type: str,
img_path: str,
fp16: bool = False,
verify: bool = False,
show: bool = False,
workspace_size: int = 1,
verbose: bool = False):
"""Convert ONNX model to TensorRT model
Args:
onnx_file (str): the path of the input ONNX file.
trt_file (str): the path to output the TensorRT file.
config (dict): MMCV configuration.
input_config (dict): contains min_shape, max_shape and \
input image path.
fp16 (bool): whether to enable fp16 mode.
verify (bool): whether to verify the outputs of TensorRT \
and ONNX are same.
show (bool): whether to show the outputs of TensorRT and ONNX.
verbose (bool): whether to print the log when generating \
TensorRT model.
"""
import tensorrt as trt
min_shape = input_config['min_shape']
max_shape = input_config['max_shape']
# create trt engine and wrapper
opt_shape_dict = {'input': [min_shape, min_shape, max_shape]}
max_workspace_size = get_GiB(workspace_size)
trt_engine = onnx2trt(
onnx_file,
opt_shape_dict,
log_level=trt.Logger.VERBOSE if verbose else trt.Logger.ERROR,
fp16_mode=fp16,
max_workspace_size=max_workspace_size)
save_dir, _ = osp.split(trt_file)
if save_dir:
os.makedirs(save_dir, exist_ok=True)
save_trt_engine(trt_engine, trt_file)
print(f'Successfully created TensorRT engine: {trt_file}')
if verify:
inputs = _prepare_input_img(
model_type=model_type, img_path=img_path, config=config)
imgs = inputs['imgs']
img_list = [imgs.unsqueeze(0)]
if max_shape[0] > 1:
# concate flip image for batch test
flip_img_list = [_.flip(-1) for _ in img_list]
img_list = [
torch.cat((ori_img, flip_img), 0)
for ori_img, flip_img in zip(img_list, flip_img_list)
]
# Get results from ONNXRuntime
ort_custom_op_path = get_onnxruntime_op_path()
session_options = ort.SessionOptions()
if osp.exists(ort_custom_op_path):
session_options.register_custom_ops_library(ort_custom_op_path)
sess = ort.InferenceSession(onnx_file, session_options)
sess.set_providers(['CPUExecutionProvider'], [{}]) # use cpu mode
onnx_output = sess.run(['output'],
{'input': img_list[0].detach().numpy()})[0][0]
# Get results from TensorRT
trt_model = TRTWrapper(trt_file, ['input'], ['output'])
with torch.no_grad():
trt_outputs = trt_model({'input': img_list[0].contiguous().cuda()})
trt_output = trt_outputs['output'][0].cpu().detach().numpy()
if show:
onnx_visualize = onnx_output.transpose(1, 2, 0)
onnx_visualize = np.clip(onnx_visualize, 0, 1)[:, :, ::-1]
trt_visualize = trt_output.transpose(1, 2, 0)
trt_visualize = np.clip(trt_visualize, 0, 1)[:, :, ::-1]
cv2.imshow('ONNXRuntime', onnx_visualize)
cv2.imshow('TensorRT', trt_visualize)
cv2.waitKey()
np.testing.assert_allclose(
onnx_output, trt_output, rtol=1e-03, atol=1e-05)
print('TensorRT and ONNXRuntime output all close.')
def parse_args():
parser = argparse.ArgumentParser(
description='Convert MMSegmentation models from ONNX to TensorRT')
parser.add_argument('config', help='Config file of the model')
parser.add_argument(
'model_type',
help='what kind of model the config belong to.',
choices=['inpainting', 'mattor', 'restorer', 'synthesizer'])
parser.add_argument('img_path', type=str, help='Image for test')
parser.add_argument('onnx_file', help='Path to the input ONNX model')
parser.add_argument(
'--trt-file',
type=str,
help='Path to the output TensorRT engine',
default='tmp.trt')
parser.add_argument(
'--max-shape',
type=int,
nargs=4,
default=[1, 3, 512, 512],
help='Maximum shape of model input.')
parser.add_argument(
'--min-shape',
type=int,
nargs=4,
default=[1, 3, 32, 32],
help='Minimum shape of model input.')
parser.add_argument(
'--workspace-size',
type=int,
default=1,
help='Max workspace size in GiB')
parser.add_argument('--fp16', action='store_true', help='Enable fp16 mode')
parser.add_argument(
'--show', action='store_true', help='Whether to show output results')
parser.add_argument(
'--verify',
action='store_true',
help='Verify the outputs of ONNXRuntime and TensorRT')
parser.add_argument(
'--verbose',
action='store_true',
help='Whether to verbose logging messages while creating \
TensorRT engine.')
args = parser.parse_args()
return args
if __name__ == '__main__':
assert is_tensorrt_plugin_loaded(), 'TensorRT plugin should be compiled.'
args = parse_args()
# check arguments
assert osp.exists(args.config), 'Config {} not found.'.format(args.config)
assert osp.exists(args.onnx_file), \
'ONNX model {} not found.'.format(args.onnx_file)
assert args.workspace_size >= 0, 'Workspace size less than 0.'
for max_value, min_value in zip(args.max_shape, args.min_shape):
assert max_value >= min_value, \
'max_shape should be larger than min shape'
config = mmcv.Config.fromfile(args.config)
config.model.pretrained = None
input_config = {
'min_shape': args.min_shape,
'max_shape': args.max_shape,
'input_path': args.img_path
}
onnx2tensorrt(
args.onnx_file,
args.trt_file,
config,
input_config,
model_type=args.model_type,
img_path=args.img_path,
fp16=args.fp16,
verify=args.verify,
show=args.show,
workspace_size=args.workspace_size,
verbose=args.verbose)
# Following strings of text style are from colorama package
bright_style, reset_style = '\x1b[1m', '\x1b[0m'
red_text, blue_text = '\x1b[31m', '\x1b[34m'
white_background = '\x1b[107m'
msg = white_background + bright_style + red_text
msg += 'DeprecationWarning: This tool will be deprecated in future. '
msg += blue_text + 'Welcome to use the unified model deployment toolbox '
msg += 'MMDeploy: https://github.com/open-mmlab/mmdeploy'
msg += reset_style
warnings.warn(msg)
| 9,445 | 34.115242 | 79 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tools/publish_model.py | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import subprocess
import torch
from packaging import version
def parse_args():
parser = argparse.ArgumentParser(
description='Process a checkpoint to be published')
parser.add_argument('in_file', help='input checkpoint filename')
parser.add_argument('out_file', help='output checkpoint filename')
args = parser.parse_args()
return args
def process_checkpoint(in_file, out_file):
checkpoint = torch.load(in_file, map_location='cpu')
# remove optimizer for smaller file size
if 'optimizer' in checkpoint:
del checkpoint['optimizer']
# if it is necessary to remove some sensitive data in checkpoint['meta'],
# add the code here.
if version.parse(torch.__version__) >= version.parse('1.6'):
torch.save(checkpoint, out_file, _use_new_zipfile_serialization=False)
else:
torch.save(checkpoint, out_file)
sha = subprocess.check_output(['sha256sum', out_file]).decode()
final_file = out_file.rstrip('.pth') + f'-{sha[:8]}.pth'
subprocess.Popen(['mv', out_file, final_file])
def main():
args = parse_args()
process_checkpoint(args.in_file, args.out_file)
if __name__ == '__main__':
main()
| 1,256 | 29.658537 | 78 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tools/pytorch2onnx.py | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import warnings
import cv2
import mmcv
import numpy as np
import onnx
import onnxruntime as rt
import torch
from mmcv.onnx import register_extra_symbolics
from mmcv.runner import load_checkpoint
from mmedit.datasets.pipelines import Compose
from mmedit.models import build_model
def pytorch2onnx(model,
input,
model_type,
opset_version=11,
show=False,
output_file='tmp.onnx',
verify=False,
dynamic_export=False):
"""Export Pytorch model to ONNX model and verify the outputs are same
between Pytorch and ONNX.
Args:
model (nn.Module): Pytorch model we want to export.
input (dict): We need to use this input to execute the model.
opset_version (int): The onnx op version. Default: 11.
show (bool): Whether print the computation graph. Default: False.
output_file (string): The path to where we store the output ONNX model.
Default: `tmp.onnx`.
verify (bool): Whether compare the outputs between Pytorch and ONNX.
Default: False.
"""
model.cpu().eval()
if model_type == 'mattor':
merged = input['merged'].unsqueeze(0)
trimap = input['trimap'].unsqueeze(0)
data = torch.cat((merged, trimap), 1)
elif model_type == 'restorer':
data = input['lq'].unsqueeze(0)
model.forward = model.forward_dummy
# pytorch has some bug in pytorch1.3, we have to fix it
# by replacing these existing op
register_extra_symbolics(opset_version)
dynamic_axes = None
if dynamic_export:
dynamic_axes = {
'input': {
0: 'batch',
2: 'height',
3: 'width'
},
'output': {
0: 'batch',
2: 'height',
3: 'width'
}
}
with torch.no_grad():
torch.onnx.export(
model,
data,
output_file,
input_names=['input'],
output_names=['output'],
export_params=True,
keep_initializers_as_inputs=False,
verbose=show,
opset_version=opset_version,
dynamic_axes=dynamic_axes)
print(f'Successfully exported ONNX model: {output_file}')
if verify:
# check by onnx
onnx_model = onnx.load(output_file)
onnx.checker.check_model(onnx_model)
if dynamic_export:
# scale image for dynamic shape test
data = torch.nn.functional.interpolate(data, scale_factor=1.1)
# concate flip image for batch test
flip_data = data.flip(-1)
data = torch.cat((data, flip_data), 0)
# get pytorch output, only concern pred_alpha
with torch.no_grad():
pytorch_result = model(data)
if isinstance(pytorch_result, (tuple, list)):
pytorch_result = pytorch_result[0]
pytorch_result = pytorch_result.detach().numpy()
# get onnx output
sess = rt.InferenceSession(output_file)
onnx_result = sess.run(None, {
'input': data.detach().numpy(),
})
# only concern pred_alpha value
if isinstance(onnx_result, (tuple, list)):
onnx_result = onnx_result[0]
if show:
pytorch_visualize = pytorch_result[0].transpose(1, 2, 0)
pytorch_visualize = np.clip(pytorch_visualize, 0, 1)[:, :, ::-1]
onnx_visualize = onnx_result[0].transpose(1, 2, 0)
onnx_visualize = np.clip(onnx_visualize, 0, 1)[:, :, ::-1]
cv2.imshow('PyTorch', pytorch_visualize)
cv2.imshow('ONNXRuntime', onnx_visualize)
cv2.waitKey()
# check the numerical value
assert np.allclose(
pytorch_result, onnx_result, rtol=1e-5,
atol=1e-5), 'The outputs are different between Pytorch and ONNX'
print('The numerical values are same between Pytorch and ONNX')
def parse_args():
parser = argparse.ArgumentParser(description='Convert MMediting to ONNX')
parser.add_argument('config', help='test config file path')
parser.add_argument('checkpoint', help='checkpoint file')
parser.add_argument(
'model_type',
help='what kind of model the config belong to.',
choices=['inpainting', 'mattor', 'restorer', 'synthesizer'])
parser.add_argument('img_path', help='path to input image file')
parser.add_argument(
'--trimap-path',
default=None,
help='path to input trimap file, used in mattor model')
parser.add_argument('--show', action='store_true', help='show onnx graph')
parser.add_argument('--output-file', type=str, default='tmp.onnx')
parser.add_argument('--opset-version', type=int, default=11)
parser.add_argument(
'--verify',
action='store_true',
help='verify the onnx model output against pytorch output')
parser.add_argument(
'--dynamic-export',
action='store_true',
help='Whether to export onnx with dynamic axis.')
args = parser.parse_args()
return args
if __name__ == '__main__':
args = parse_args()
model_type = args.model_type
if model_type == 'mattor' and args.trimap_path is None:
raise ValueError('Please set `--trimap-path` to convert mattor model.')
assert args.opset_version == 11, 'MMEditing only support opset 11 now'
config = mmcv.Config.fromfile(args.config)
config.model.pretrained = None
# ONNX does not support spectral norm
if model_type == 'mattor':
if hasattr(config.model.backbone.encoder, 'with_spectral_norm'):
config.model.backbone.encoder.with_spectral_norm = False
config.model.backbone.decoder.with_spectral_norm = False
config.test_cfg.metrics = None
# build the model
model = build_model(config.model, test_cfg=config.test_cfg)
checkpoint = load_checkpoint(model, args.checkpoint, map_location='cpu')
# remove alpha from test_pipeline
if model_type == 'mattor':
keys_to_remove = ['alpha', 'ori_alpha']
elif model_type == 'restorer':
keys_to_remove = ['gt', 'gt_path']
for key in keys_to_remove:
for pipeline in list(config.test_pipeline):
if 'key' in pipeline and key == pipeline['key']:
config.test_pipeline.remove(pipeline)
if 'keys' in pipeline and key in pipeline['keys']:
pipeline['keys'].remove(key)
if len(pipeline['keys']) == 0:
config.test_pipeline.remove(pipeline)
if 'meta_keys' in pipeline and key in pipeline['meta_keys']:
pipeline['meta_keys'].remove(key)
# build the data pipeline
test_pipeline = Compose(config.test_pipeline)
# prepare data
if model_type == 'mattor':
data = dict(merged_path=args.img_path, trimap_path=args.trimap_path)
elif model_type == 'restorer':
data = dict(lq_path=args.img_path)
data = test_pipeline(data)
# convert model to onnx file
pytorch2onnx(
model,
data,
model_type,
opset_version=args.opset_version,
show=args.show,
output_file=args.output_file,
verify=args.verify,
dynamic_export=args.dynamic_export)
# Following strings of text style are from colorama package
bright_style, reset_style = '\x1b[1m', '\x1b[0m'
red_text, blue_text = '\x1b[31m', '\x1b[34m'
white_background = '\x1b[107m'
msg = white_background + bright_style + red_text
msg += 'DeprecationWarning: This tool will be deprecated in future. '
msg += blue_text + 'Welcome to use the unified model deployment toolbox '
msg += 'MMDeploy: https://github.com/open-mmlab/mmdeploy'
msg += reset_style
warnings.warn(msg)
| 7,975 | 35.420091 | 79 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tools/deploy_test.py | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import warnings
from typing import Any
import mmcv
import torch
from mmcv import Config, DictAction
from mmcv.parallel import MMDataParallel
from torch import nn
from mmedit.apis import single_gpu_test
from mmedit.core.export import ONNXRuntimeEditing
from mmedit.datasets import build_dataloader, build_dataset
from mmedit.models import BasicRestorer, build_model
class TensorRTRestorerGenerator(nn.Module):
"""Inner class for tensorrt restorer model inference
Args:
trt_file (str): The path to the tensorrt file.
device_id (int): Which device to place the model.
"""
def __init__(self, trt_file: str, device_id: int):
super().__init__()
from mmcv.tensorrt import TRTWrapper, load_tensorrt_plugin
try:
load_tensorrt_plugin()
except (ImportError, ModuleNotFoundError):
warnings.warn('If input model has custom op from mmcv, \
you may have to build mmcv with TensorRT from source.')
model = TRTWrapper(
trt_file, input_names=['input'], output_names=['output'])
self.device_id = device_id
self.model = model
def forward(self, x):
with torch.cuda.device(self.device_id), torch.no_grad():
seg_pred = self.model({'input': x})['output']
seg_pred = seg_pred.detach().cpu()
return seg_pred
class TensorRTRestorer(nn.Module):
"""A warper class for tensorrt restorer
Args:
base_model (Any): The base model build from config.
trt_file (str): The path to the tensorrt file.
device_id (int): Which device to place the model.
"""
def __init__(self, base_model: Any, trt_file: str, device_id: int):
super().__init__()
self.base_model = base_model
restorer_generator = TensorRTRestorerGenerator(
trt_file=trt_file, device_id=device_id)
base_model.generator = restorer_generator
def forward(self, lq, gt=None, test_mode=False, **kwargs):
return self.base_model(lq, gt=gt, test_mode=test_mode, **kwargs)
class TensorRTEditing(nn.Module):
"""A class for testing tensorrt deployment
Args:
trt_file (str): The path to the tensorrt file.
cfg (Any): The configuration of the testing, \
decided by the config file.
device_id (int): Which device to place the model.
"""
def __init__(self, trt_file: str, cfg: Any, device_id: int):
super().__init__()
base_model = build_model(
cfg.model, train_cfg=None, test_cfg=cfg.test_cfg)
if isinstance(base_model, BasicRestorer):
WrapperClass = TensorRTRestorer
self.wrapper = WrapperClass(base_model, trt_file, device_id)
def forward(self, **kwargs):
return self.wrapper(**kwargs)
def parse_args():
parser = argparse.ArgumentParser(description='mmediting tester')
parser.add_argument('config', help='test config file path')
parser.add_argument('model', help='input model file')
parser.add_argument(
'backend',
help='backend of the model.',
choices=['onnxruntime', 'tensorrt'])
parser.add_argument('--out', help='output result pickle file')
parser.add_argument(
'--save-path',
default=None,
type=str,
help='path to store images and if not given, will not save image')
parser.add_argument(
'--cfg-options',
nargs='+',
action=DictAction,
help='override some settings in the used config, the key-value pair '
'in xxx=yyy format will be merged into config file. If the value to '
'be overwritten is a list, it should be like key="[a,b]" or key=a,b '
'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" '
'Note that the quotation marks are necessary and that no white space '
'is allowed.')
args = parser.parse_args()
return args
def main():
args = parse_args()
cfg = Config.fromfile(args.config)
if args.cfg_options is not None:
cfg.merge_from_dict(args.cfg_options)
# init distributed env first, since logger depends on the dist info.
distributed = False
# build the dataloader
dataset = build_dataset(cfg.data.test)
loader_cfg = {
**dict((k, cfg.data[k]) for k in ['workers_per_gpu'] if k in cfg.data),
**dict(
samples_per_gpu=1,
drop_last=False,
shuffle=False,
dist=distributed),
**cfg.data.get('test_dataloader', {})
}
data_loader = build_dataloader(dataset, **loader_cfg)
# build the model
if args.backend == 'onnxruntime':
model = ONNXRuntimeEditing(args.model, cfg=cfg, device_id=0)
elif args.backend == 'tensorrt':
model = TensorRTEditing(args.model, cfg=cfg, device_id=0)
args.save_image = args.save_path is not None
model = MMDataParallel(model, device_ids=[0])
outputs = single_gpu_test(
model,
data_loader,
save_path=args.save_path,
save_image=args.save_image)
print()
# print metrics
stats = dataset.evaluate(outputs)
for stat in stats:
print('Eval-{}: {}'.format(stat, stats[stat]))
# save result pickle
if args.out:
print('writing results to {}'.format(args.out))
mmcv.dump(outputs, args.out)
if __name__ == '__main__':
main()
# Following strings of text style are from colorama package
bright_style, reset_style = '\x1b[1m', '\x1b[0m'
red_text, blue_text = '\x1b[31m', '\x1b[34m'
white_background = '\x1b[107m'
msg = white_background + bright_style + red_text
msg += 'DeprecationWarning: This tool will be deprecated in future. '
msg += blue_text + 'Welcome to use the unified model deployment toolbox '
msg += 'MMDeploy: https://github.com/open-mmlab/mmdeploy'
msg += reset_style
warnings.warn(msg)
| 5,983 | 31.879121 | 79 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tools/train.py | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import copy
import os
import os.path as osp
import time
import mmcv
import torch
import torch.distributed as dist
from mmcv import Config, DictAction
from mmcv.runner import init_dist
from mmedit import __version__
from mmedit.apis import init_random_seed, set_random_seed, train_model
from mmedit.datasets import build_dataset
from mmedit.models import build_model
from mmedit.utils import collect_env, get_root_logger, setup_multi_processes
def parse_args():
parser = argparse.ArgumentParser(description='Train an editor')
parser.add_argument('config', help='train config file path')
parser.add_argument('--work-dir', help='the dir to save logs and models')
parser.add_argument(
'--resume-from', help='the checkpoint file to resume from')
parser.add_argument(
'--no-validate',
action='store_true',
help='whether not to evaluate the checkpoint during training')
parser.add_argument(
'--gpus',
type=int,
default=1,
help='number of gpus to use '
'(only applicable to non-distributed training)')
parser.add_argument('--seed', type=int, default=None, help='random seed')
parser.add_argument(
'--diff_seed',
action='store_true',
help='Whether or not set different seeds for different ranks')
parser.add_argument(
'--deterministic',
action='store_true',
help='whether to set deterministic options for CUDNN backend.')
parser.add_argument(
'--cfg-options',
nargs='+',
action=DictAction,
help='override some settings in the used config, the key-value pair '
'in xxx=yyy format will be merged into config file. If the value to '
'be overwritten is a list, it should be like key="[a,b]" or key=a,b '
'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" '
'Note that the quotation marks are necessary and that no white space '
'is allowed.')
parser.add_argument(
'--launcher',
choices=['none', 'pytorch', 'slurm', 'mpi'],
default='none',
help='job launcher')
parser.add_argument('--local_rank', type=int, default=0)
parser.add_argument(
'--autoscale-lr',
action='store_true',
help='automatically scale lr with the number of gpus')
args = parser.parse_args()
if 'LOCAL_RANK' not in os.environ:
os.environ['LOCAL_RANK'] = str(args.local_rank)
return args
def main():
args = parse_args()
cfg = Config.fromfile(args.config)
if args.cfg_options is not None:
cfg.merge_from_dict(args.cfg_options)
# set multi-process settings
setup_multi_processes(cfg)
# set cudnn_benchmark
if cfg.get('cudnn_benchmark', False):
torch.backends.cudnn.benchmark = True
# update configs according to CLI args
if args.work_dir is not None:
cfg.work_dir = args.work_dir
if args.resume_from is not None:
cfg.resume_from = args.resume_from
cfg.gpus = args.gpus
if args.autoscale_lr:
# apply the linear scaling rule (https://arxiv.org/abs/1706.02677)
cfg.optimizer['lr'] = cfg.optimizer['lr'] * cfg.gpus / 8
# init distributed env first, since logger depends on the dist info.
if args.launcher == 'none':
distributed = False
else:
distributed = True
init_dist(args.launcher, **cfg.dist_params)
# create work_dir
mmcv.mkdir_or_exist(osp.abspath(cfg.work_dir))
# init the logger before other steps
timestamp = time.strftime('%Y%m%d_%H%M%S', time.localtime())
log_file = osp.join(cfg.work_dir, f'{timestamp}.log')
logger = get_root_logger(log_file=log_file, log_level=cfg.log_level)
# log env info
env_info_dict = collect_env.collect_env()
env_info = '\n'.join([f'{k}: {v}' for k, v in env_info_dict.items()])
dash_line = '-' * 60 + '\n'
logger.info('Environment info:\n' + dash_line + env_info + '\n' +
dash_line)
# log some basic info
logger.info('Distributed training: {}'.format(distributed))
logger.info('mmedit Version: {}'.format(__version__))
logger.info('Config:\n{}'.format(cfg.text))
# set random seeds
seed = init_random_seed(args.seed)
seed = seed + dist.get_rank() if args.diff_seed else seed
logger.info('Set random seed to {}, deterministic: {}'.format(
seed, args.deterministic))
set_random_seed(seed, deterministic=args.deterministic)
cfg.seed = seed
model = build_model(
cfg.model, train_cfg=cfg.train_cfg, test_cfg=cfg.test_cfg)
datasets = [build_dataset(cfg.data.train)]
if len(cfg.workflow) == 2:
val_dataset = copy.deepcopy(cfg.data.val)
val_dataset.pipeline = cfg.data.train.pipeline
datasets.append(build_dataset(val_dataset))
if cfg.checkpoint_config is not None:
# save version, config file content and class names in
# checkpoints as meta data
cfg.checkpoint_config.meta = dict(
mmedit_version=__version__,
config=cfg.text,
)
# meta information
meta = dict()
if cfg.get('exp_name', None) is None:
cfg['exp_name'] = osp.splitext(osp.basename(cfg.work_dir))[0]
meta['exp_name'] = cfg.exp_name
meta['mmedit Version'] = __version__
meta['seed'] = seed
meta['env_info'] = env_info
# add an attribute for visualization convenience
train_model(
model,
datasets,
cfg,
distributed=distributed,
validate=(not args.no_validate),
timestamp=timestamp,
meta=meta)
if __name__ == '__main__':
main()
| 5,738 | 32.758824 | 78 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tools/deployment/mmedit_handler.py | # Copyright (c) OpenMMLab. All rights reserved.
import os
import random
import string
from io import BytesIO
import PIL.Image as Image
import torch
from ts.torch_handler.base_handler import BaseHandler
from mmedit.apis import init_model, restoration_inference
from mmedit.core import tensor2img
class MMEditHandler(BaseHandler):
def initialize(self, context):
print('MMEditHandler.initialize is called')
properties = context.system_properties
self.map_location = 'cuda' if torch.cuda.is_available() else 'cpu'
self.device = torch.device(self.map_location + ':' +
str(properties.get('gpu_id')) if torch.cuda.
is_available() else self.map_location)
self.manifest = context.manifest
model_dir = properties.get('model_dir')
serialized_file = self.manifest['model']['serializedFile']
checkpoint = os.path.join(model_dir, serialized_file)
self.config_file = os.path.join(model_dir, 'config.py')
self.model = init_model(self.config_file, checkpoint, self.device)
self.initialized = True
def preprocess(self, data, *args, **kwargs):
body = data[0].get('data') or data[0].get('body')
result = Image.open(BytesIO(body))
# data preprocess is in inference.
return result
def inference(self, data, *args, **kwargs):
# generate temp image path for restoration_inference
temp_name = ''.join(
random.sample(string.ascii_letters + string.digits, 18))
temp_path = f'./{temp_name}.png'
data.save(temp_path)
results = restoration_inference(self.model, temp_path)
# delete the temp image path
os.remove(temp_path)
return results
def postprocess(self, data):
# convert torch tensor to numpy and then convert to bytes
output_list = []
for data_ in data:
data_np = tensor2img(data_)
data_byte = data_np.tobytes()
output_list.append(data_byte)
return output_list
| 2,099 | 34 | 79 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tools/deployment/mmedit2torchserve.py | # Copyright (c) OpenMMLab. All rights reserved.
from argparse import ArgumentParser, Namespace
from pathlib import Path
from tempfile import TemporaryDirectory
import mmcv
try:
from model_archiver.model_packaging import package_model
from model_archiver.model_packaging_utils import ModelExportUtils
except ImportError:
package_model = None
def mmedit2torchserve(
config_file: str,
checkpoint_file: str,
output_folder: str,
model_name: str,
model_version: str = '1.0',
force: bool = False,
):
"""Converts MMEditing model (config + checkpoint) to TorchServe `.mar`.
Args:
config_file:
In MMEditing config format.
The contents vary for each task repository.
checkpoint_file:
In MMEditing checkpoint format.
The contents vary for each task repository.
output_folder:
Folder where `{model_name}.mar` will be created.
The file created will be in TorchServe archive format.
model_name:
If not None, used for naming the `{model_name}.mar` file
that will be created under `output_folder`.
If None, `{Path(checkpoint_file).stem}` will be used.
model_version:
Model's version.
force:
If True, if there is an existing `{model_name}.mar`
file under `output_folder` it will be overwritten.
"""
mmcv.mkdir_or_exist(output_folder)
config = mmcv.Config.fromfile(config_file)
with TemporaryDirectory() as tmpdir:
config.dump(f'{tmpdir}/config.py')
args_ = Namespace(
**{
'model_file': f'{tmpdir}/config.py',
'serialized_file': checkpoint_file,
'handler': f'{Path(__file__).parent}/mmedit_handler.py',
'model_name': model_name or Path(checkpoint_file).stem,
'version': model_version,
'export_path': output_folder,
'force': force,
'requirements_file': None,
'extra_files': None,
'runtime': 'python',
'archive_format': 'default'
})
print(args_.model_name)
manifest = ModelExportUtils.generate_manifest_json(args_)
package_model(args_, manifest)
def parse_args():
parser = ArgumentParser(
description='Convert MMEditing models to TorchServe `.mar` format.')
parser.add_argument('config', type=str, help='config file path')
parser.add_argument('checkpoint', type=str, help='checkpoint file path')
parser.add_argument(
'--output-folder',
type=str,
required=True,
help='Folder where `{model_name}.mar` will be created.')
parser.add_argument(
'--model-name',
type=str,
default=None,
help='If not None, used for naming the `{model_name}.mar`'
'file that will be created under `output_folder`.'
'If None, `{Path(checkpoint_file).stem}` will be used.')
parser.add_argument(
'--model-version',
type=str,
default='1.0',
help='Number used for versioning.')
parser.add_argument(
'-f',
'--force',
action='store_true',
help='overwrite the existing `{model_name}.mar`')
args_ = parser.parse_args()
return args_
if __name__ == '__main__':
args = parse_args()
if package_model is None:
raise ImportError('`torch-model-archiver` is required.'
'Try: pip install torch-model-archiver')
mmedit2torchserve(args.config, args.checkpoint, args.output_folder,
args.model_name, args.model_version, args.force)
| 3,725 | 32.567568 | 76 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_inference.py | # Copyright (c) OpenMMLab. All rights reserved.
import os
import shutil
import pytest
import torch
from mmedit.apis import (init_model, restoration_video_inference,
video_interpolation_inference)
def test_restoration_video_inference():
if torch.cuda.is_available():
# recurrent framework (BasicVSR)
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'
output = restoration_video_inference(model, img_dir, window_size,
start_idx, filename_tmpl)
assert output.shape == (1, 7, 3, 256, 448)
# sliding-window framework (EDVR)
window_size = 5
model = init_model(
'./configs/restorers/edvr/edvrm_wotsa_x4_g8_600k_reds.py',
None,
device='cuda')
output = restoration_video_inference(model, img_dir, window_size,
start_idx, filename_tmpl)
assert output.shape == (1, 7, 3, 256, 448)
# without demo_pipeline
model.cfg.test_pipeline = model.cfg.demo_pipeline
model.cfg.pop('demo_pipeline')
output = restoration_video_inference(model, img_dir, window_size,
start_idx, filename_tmpl)
assert output.shape == (1, 7, 3, 256, 448)
# without test_pipeline and demo_pipeline
model.cfg.val_pipeline = model.cfg.test_pipeline
model.cfg.pop('test_pipeline')
output = restoration_video_inference(model, img_dir, window_size,
start_idx, filename_tmpl)
assert output.shape == (1, 7, 3, 256, 448)
# the first element in the pipeline must be 'GenerateSegmentIndices'
with pytest.raises(TypeError):
model.cfg.val_pipeline = model.cfg.val_pipeline[1:]
output = restoration_video_inference(model, img_dir, window_size,
start_idx, filename_tmpl)
# video (mp4) input
model = init_model(
'./configs/restorers/basicvsr/basicvsr_reds4.py',
None,
device='cuda')
img_dir = './tests/data/test_inference.mp4'
window_size = 0
start_idx = 1
filename_tmpl = 'im{}.png'
output = restoration_video_inference(model, img_dir, window_size,
start_idx, filename_tmpl)
assert output.shape == (1, 5, 3, 256, 256)
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=['inputs']),
dict(type='FramesToTensor', keys=['inputs']),
dict(
type='Collect', keys=['inputs'], meta_keys=['inputs_path', 'key'])
]
input_dir = './tests/data/vimeo90k/00001/0266'
output_dir = './tests/data/vimeo90k/00001/out'
os.mkdir(output_dir)
video_interpolation_inference(model, input_dir, output_dir, batch_size=10)
input_dir = './tests/data/test_inference.mp4'
output_dir = './tests/data/test_inference_out.mp4'
video_interpolation_inference(model, input_dir, output_dir)
with pytest.raises(AssertionError):
input_dir = './tests/data/test_inference.mp4'
output_dir = './tests/data/test_inference_out.mp4'
video_interpolation_inference(
model, input_dir, output_dir, fps_multiplier=-1)
if torch.cuda.is_available():
model = init_model(
'./configs/video_interpolators/cain/cain_b5_320k_vimeo-triplet.py',
None,
device='cuda')
model.cfg['demo_pipeline'] = [
dict(
type='LoadImageFromFileList',
io_backend='disk',
key='inputs',
channel_order='rgb'),
dict(type='RescaleToZeroOne', keys=['inputs']),
dict(type='FramesToTensor', keys=['inputs']),
dict(
type='Collect',
keys=['inputs'],
meta_keys=['inputs_path', 'key'])
]
input_dir = './tests/data/vimeo90k/00001/0266'
output_dir = './tests/data/vimeo90k/00001'
video_interpolation_inference(
model, input_dir, output_dir, batch_size=10)
input_dir = './tests/data/test_inference.mp4'
output_dir = './tests/data/test_inference_out.mp4'
video_interpolation_inference(model, input_dir, output_dir)
with pytest.raises(AssertionError):
input_dir = './tests/data/test_inference.mp4'
output_dir = './tests/data/test_inference_out.mp4'
video_interpolation_inference(
model, input_dir, output_dir, fps_multiplier=-1)
shutil.rmtree('./tests/data/vimeo90k/00001/out')
os.remove('./tests/data/test_inference_out.mp4')
| 5,333 | 36.829787 | 79 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_runtime/test_optimizer.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch
import torch.nn as nn
from mmedit.core import build_optimizers
class ExampleModel(nn.Module):
def __init__(self):
super().__init__()
self.model1 = nn.Conv2d(3, 8, kernel_size=3)
self.model2 = nn.Conv2d(3, 4, kernel_size=3)
def forward(self, x):
return x
def test_build_optimizers():
base_lr = 0.0001
base_wd = 0.0002
momentum = 0.9
# basic config with ExampleModel
optimizer_cfg = dict(
model1=dict(
type='SGD', lr=base_lr, weight_decay=base_wd, momentum=momentum),
model2=dict(
type='SGD', lr=base_lr, weight_decay=base_wd, momentum=momentum))
model = ExampleModel()
optimizers = build_optimizers(model, optimizer_cfg)
param_dict = dict(model.named_parameters())
assert isinstance(optimizers, dict)
for i in range(2):
optimizer = optimizers[f'model{i+1}']
param_groups = optimizer.param_groups[0]
assert isinstance(optimizer, torch.optim.SGD)
assert optimizer.defaults['lr'] == base_lr
assert optimizer.defaults['momentum'] == momentum
assert optimizer.defaults['weight_decay'] == base_wd
assert len(param_groups['params']) == 2
assert torch.equal(param_groups['params'][0],
param_dict[f'model{i+1}.weight'])
assert torch.equal(param_groups['params'][1],
param_dict[f'model{i+1}.bias'])
# basic config with Parallel model
model = torch.nn.DataParallel(ExampleModel())
optimizers = build_optimizers(model, optimizer_cfg)
param_dict = dict(model.named_parameters())
assert isinstance(optimizers, dict)
for i in range(2):
optimizer = optimizers[f'model{i+1}']
param_groups = optimizer.param_groups[0]
assert isinstance(optimizer, torch.optim.SGD)
assert optimizer.defaults['lr'] == base_lr
assert optimizer.defaults['momentum'] == momentum
assert optimizer.defaults['weight_decay'] == base_wd
assert len(param_groups['params']) == 2
assert torch.equal(param_groups['params'][0],
param_dict[f'module.model{i+1}.weight'])
assert torch.equal(param_groups['params'][1],
param_dict[f'module.model{i+1}.bias'])
# basic config with ExampleModel (one optimizer)
optimizer_cfg = dict(
type='SGD', lr=base_lr, weight_decay=base_wd, momentum=momentum)
model = ExampleModel()
optimizer = build_optimizers(model, optimizer_cfg)
param_dict = dict(model.named_parameters())
assert isinstance(optimizers, dict)
param_groups = optimizer.param_groups[0]
assert isinstance(optimizer, torch.optim.SGD)
assert optimizer.defaults['lr'] == base_lr
assert optimizer.defaults['momentum'] == momentum
assert optimizer.defaults['weight_decay'] == base_wd
assert len(param_groups['params']) == 4
assert torch.equal(param_groups['params'][0], param_dict['model1.weight'])
assert torch.equal(param_groups['params'][1], param_dict['model1.bias'])
assert torch.equal(param_groups['params'][2], param_dict['model2.weight'])
assert torch.equal(param_groups['params'][3], param_dict['model2.bias'])
# basic config with Parallel model (one optimizer)
model = torch.nn.DataParallel(ExampleModel())
optimizer = build_optimizers(model, optimizer_cfg)
param_dict = dict(model.named_parameters())
assert isinstance(optimizers, dict)
param_groups = optimizer.param_groups[0]
assert isinstance(optimizer, torch.optim.SGD)
assert optimizer.defaults['lr'] == base_lr
assert optimizer.defaults['momentum'] == momentum
assert optimizer.defaults['weight_decay'] == base_wd
assert len(param_groups['params']) == 4
assert torch.equal(param_groups['params'][0],
param_dict['module.model1.weight'])
assert torch.equal(param_groups['params'][1],
param_dict['module.model1.bias'])
assert torch.equal(param_groups['params'][2],
param_dict['module.model2.weight'])
assert torch.equal(param_groups['params'][3],
param_dict['module.model2.bias'])
| 4,279 | 40.960784 | 78 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_runtime/test_visual_hook.py | # Copyright (c) OpenMMLab. All rights reserved.
import os.path as osp
import tempfile
from unittest.mock import MagicMock
import mmcv
import numpy as np
import pytest
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, Dataset
from mmedit.core import VisualizationHook
from mmedit.utils import get_root_logger
class ExampleDataset(Dataset):
def __getitem__(self, idx):
img = torch.zeros((3, 10, 10))
img[:, 2:9, :] = 1.
results = dict(imgs=img)
return results
def __len__(self):
return 1
class ExampleModel(nn.Module):
def __init__(self):
super().__init__()
self.test_cfg = None
def train_step(self, data_batch, optimizer):
output = dict(results=dict(img=data_batch['imgs']))
return output
def test_visual_hook():
with pytest.raises(
AssertionError), tempfile.TemporaryDirectory() as tmpdir:
VisualizationHook(tmpdir, [1, 2, 3])
test_dataset = ExampleDataset()
test_dataset.evaluate = MagicMock(return_value=dict(test='success'))
img = torch.zeros((1, 3, 10, 10))
img[:, :, 2:9, :] = 1.
model = ExampleModel()
data_loader = DataLoader(
test_dataset, batch_size=1, sampler=None, num_workers=0, shuffle=False)
with tempfile.TemporaryDirectory() as tmpdir:
visual_hook = VisualizationHook(
tmpdir, ['img'], interval=8, rerange=False)
runner = mmcv.runner.IterBasedRunner(
model=model,
optimizer=None,
work_dir=tmpdir,
logger=get_root_logger())
runner.register_hook(visual_hook)
runner.run([data_loader], [('train', 10)], 10)
img_saved = mmcv.imread(
osp.join(tmpdir, 'iter_8.png'), flag='unchanged')
np.testing.assert_almost_equal(img_saved,
img[0].permute(1, 2, 0) * 255)
with tempfile.TemporaryDirectory() as tmpdir:
visual_hook = VisualizationHook(
tmpdir, ['img'], interval=8, rerange=True)
runner = mmcv.runner.IterBasedRunner(
model=model,
optimizer=None,
work_dir=tmpdir,
logger=get_root_logger())
runner.register_hook(visual_hook)
runner.run([data_loader], [('train', 10)], 10)
img_saved = mmcv.imread(
osp.join(tmpdir, 'iter_8.png'), flag='unchanged')
assert osp.exists(osp.join(tmpdir, 'iter_8.png'))
| 2,480 | 28.891566 | 79 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_runtime/test_dataset_builder.py | # Copyright (c) OpenMMLab. All rights reserved.
import math
from torch.utils.data import ConcatDataset, RandomSampler, SequentialSampler
from mmedit.datasets import (DATASETS, RepeatDataset, build_dataloader,
build_dataset)
from mmedit.datasets.samplers import DistributedSampler
@DATASETS.register_module()
class ToyDataset:
def __init__(self, ann_file=None, cnt=0):
self.ann_file = ann_file
self.cnt = cnt
def __item__(self, idx):
return idx
def __len__(self):
return 100
@DATASETS.register_module()
class ToyDatasetWithAnnFile:
def __init__(self, ann_file):
self.ann_file = ann_file
def __item__(self, idx):
return idx
def __len__(self):
return 100
def test_build_dataset():
cfg = dict(type='ToyDataset')
dataset = build_dataset(cfg)
assert isinstance(dataset, ToyDataset)
assert dataset.cnt == 0
# test default_args
dataset = build_dataset(cfg, default_args=dict(cnt=1))
assert isinstance(dataset, ToyDataset)
assert dataset.cnt == 1
# test RepeatDataset
cfg = dict(type='RepeatDataset', dataset=dict(type='ToyDataset'), times=3)
dataset = build_dataset(cfg)
assert isinstance(dataset, RepeatDataset)
assert isinstance(dataset.dataset, ToyDataset)
assert dataset.times == 3
# test when ann_file is a list
cfg = dict(
type='ToyDatasetWithAnnFile', ann_file=['ann_file_a', 'ann_file_b'])
dataset = build_dataset(cfg)
assert isinstance(dataset, ConcatDataset)
assert isinstance(dataset.datasets, list)
assert isinstance(dataset.datasets[0], ToyDatasetWithAnnFile)
assert dataset.datasets[0].ann_file == 'ann_file_a'
assert isinstance(dataset.datasets[1], ToyDatasetWithAnnFile)
assert dataset.datasets[1].ann_file == 'ann_file_b'
# test concat dataset
cfg = (dict(type='ToyDataset'),
dict(type='ToyDatasetWithAnnFile', ann_file='ann_file'))
dataset = build_dataset(cfg)
assert isinstance(dataset, ConcatDataset)
assert isinstance(dataset.datasets, list)
assert isinstance(dataset.datasets[0], ToyDataset)
assert isinstance(dataset.datasets[1], ToyDatasetWithAnnFile)
def test_build_dataloader():
dataset = ToyDataset()
samples_per_gpu = 3
# dist=True, shuffle=True, 1GPU
dataloader = build_dataloader(
dataset, samples_per_gpu=samples_per_gpu, workers_per_gpu=2)
assert dataloader.batch_size == samples_per_gpu
assert len(dataloader) == int(math.ceil(len(dataset) / samples_per_gpu))
assert isinstance(dataloader.sampler, DistributedSampler)
assert dataloader.sampler.shuffle
# dist=True, shuffle=False, 1GPU
dataloader = build_dataloader(
dataset,
samples_per_gpu=samples_per_gpu,
workers_per_gpu=2,
shuffle=False)
assert dataloader.batch_size == samples_per_gpu
assert len(dataloader) == int(math.ceil(len(dataset) / samples_per_gpu))
assert isinstance(dataloader.sampler, DistributedSampler)
assert not dataloader.sampler.shuffle
# dist=True, shuffle=True, 8GPU
dataloader = build_dataloader(
dataset,
samples_per_gpu=samples_per_gpu,
workers_per_gpu=2,
num_gpus=8)
assert dataloader.batch_size == samples_per_gpu
assert len(dataloader) == int(math.ceil(len(dataset) / samples_per_gpu))
assert dataloader.num_workers == 2
# dist=False, shuffle=True, 1GPU
dataloader = build_dataloader(
dataset,
samples_per_gpu=samples_per_gpu,
workers_per_gpu=2,
dist=False)
assert dataloader.batch_size == samples_per_gpu
assert len(dataloader) == int(math.ceil(len(dataset) / samples_per_gpu))
assert isinstance(dataloader.sampler, RandomSampler)
assert dataloader.num_workers == 2
# dist=False, shuffle=False, 1GPU
dataloader = build_dataloader(
dataset,
samples_per_gpu=3,
workers_per_gpu=2,
shuffle=False,
dist=False)
assert dataloader.batch_size == samples_per_gpu
assert len(dataloader) == int(math.ceil(len(dataset) / samples_per_gpu))
assert isinstance(dataloader.sampler, SequentialSampler)
assert dataloader.num_workers == 2
# dist=False, shuffle=True, 8GPU
dataloader = build_dataloader(
dataset, samples_per_gpu=3, workers_per_gpu=2, num_gpus=8, dist=False)
assert dataloader.batch_size == samples_per_gpu * 8
assert len(dataloader) == int(
math.ceil(len(dataset) / samples_per_gpu / 8))
assert isinstance(dataloader.sampler, RandomSampler)
assert dataloader.num_workers == 16
| 4,660 | 32.056738 | 78 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_runtime/test_eval_hook.py | # Copyright (c) OpenMMLab. All rights reserved.
import logging
import tempfile
from unittest.mock import MagicMock
import mmcv.runner
import pytest
import torch
import torch.nn as nn
from mmcv.runner import obj_from_dict
from torch.utils.data import DataLoader, Dataset
from mmedit.core import EvalIterHook
class ExampleDataset(Dataset):
def __getitem__(self, idx):
results = dict(imgs=torch.tensor([1]))
return results
def __len__(self):
return 1
class ExampleModel(nn.Module):
def __init__(self):
super().__init__()
self.test_cfg = None
self.conv = nn.Conv2d(3, 3, 3)
def forward(self, imgs, test_mode=False, **kwargs):
return imgs
def train_step(self, data_batch, optimizer):
rlt = self.forward(data_batch)
return dict(result=rlt)
def test_eval_hook():
with pytest.raises(TypeError):
test_dataset = ExampleModel()
data_loader = [
DataLoader(
test_dataset,
batch_size=1,
sampler=None,
num_worker=0,
shuffle=False)
]
EvalIterHook(data_loader)
test_dataset = ExampleDataset()
test_dataset.evaluate = MagicMock(return_value=dict(test='success'))
loader = DataLoader(test_dataset, batch_size=1)
model = ExampleModel()
data_loader = DataLoader(
test_dataset, batch_size=1, sampler=None, num_workers=0, shuffle=False)
eval_hook = EvalIterHook(data_loader)
optim_cfg = dict(type='Adam', lr=2e-4, betas=(0.9, 0.999))
optimizer = obj_from_dict(optim_cfg, torch.optim,
dict(params=model.parameters()))
with tempfile.TemporaryDirectory() as tmpdir:
runner = mmcv.runner.IterBasedRunner(
model=model,
optimizer=optimizer,
work_dir=tmpdir,
logger=logging.getLogger())
runner.register_hook(eval_hook)
runner.run([loader], [('train', 1)], 1)
test_dataset.evaluate.assert_called_with([torch.tensor([1])],
logger=runner.logger)
| 2,150 | 28.067568 | 79 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_runtime/test_apis.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch
from mmedit.apis.train import init_random_seed, set_random_seed
def test_init_random_seed():
init_random_seed(0, device='cpu')
init_random_seed(device='cpu')
# test on gpu
if torch.cuda.is_available():
init_random_seed(0, device='cuda')
init_random_seed(device='cuda')
def test_set_random_seed():
set_random_seed(0, deterministic=False)
set_random_seed(0, deterministic=True)
| 482 | 24.421053 | 63 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_runtime/test_ema_hook.py | # Copyright (c) OpenMMLab. All rights reserved.
from copy import deepcopy
import pytest
import torch
import torch.nn as nn
from packaging import version
from torch.nn.parallel import DataParallel
from mmedit.core.hooks import ExponentialMovingAverageHook
class SimpleModule(nn.Module):
def __init__(self):
super().__init__()
self.a = nn.Parameter(torch.tensor([1., 2.]))
if version.parse(torch.__version__) >= version.parse('1.7.0'):
self.register_buffer('b', torch.tensor([2., 3.]), persistent=True)
self.register_buffer('c', torch.tensor([0., 1.]), persistent=False)
else:
self.register_buffer('b', torch.tensor([2., 3.]))
self.c = torch.tensor([0., 1.])
class SimpleModel(nn.Module):
def __init__(self) -> None:
super().__init__()
self.module_a = SimpleModule()
self.module_b = SimpleModule()
self.module_a_ema = SimpleModule()
self.module_b_ema = SimpleModule()
class SimpleModelNoEMA(nn.Module):
def __init__(self) -> None:
super().__init__()
self.module_a = SimpleModule()
self.module_b = SimpleModule()
class SimpleRunner:
def __init__(self):
self.model = SimpleModel()
self.iter = 0
class TestEMA:
@classmethod
def setup_class(cls):
cls.default_config = dict(
module_keys=('module_a_ema', 'module_b_ema'),
interval=1,
interp_cfg=dict(momentum=0.5))
cls.runner = SimpleRunner()
@torch.no_grad()
def test_ema_hook(self):
cfg_ = deepcopy(self.default_config)
cfg_['interval'] = -1
ema = ExponentialMovingAverageHook(**cfg_)
ema.before_run(self.runner)
ema.after_train_iter(self.runner)
module_a = self.runner.model.module_a
module_a_ema = self.runner.model.module_a_ema
ema_states = module_a_ema.state_dict()
assert torch.equal(ema_states['a'], torch.tensor([1., 2.]))
ema = ExponentialMovingAverageHook(**self.default_config)
ema.after_train_iter(self.runner)
ema_states = module_a_ema.state_dict()
assert torch.equal(ema_states['a'], torch.tensor([1., 2.]))
module_a.b /= 2.
module_a.a.data /= 2.
module_a.c /= 2.
self.runner.iter += 1
ema.after_train_iter(self.runner)
ema_states = module_a_ema.state_dict()
assert torch.equal(self.runner.model.module_a.a,
torch.tensor([0.5, 1.]))
assert torch.equal(ema_states['a'], torch.tensor([0.75, 1.5]))
assert torch.equal(ema_states['b'], torch.tensor([1., 1.5]))
assert 'c' not in ema_states
# check for the validity of args
with pytest.raises(AssertionError):
_ = ExponentialMovingAverageHook(module_keys=['a'])
with pytest.raises(AssertionError):
_ = ExponentialMovingAverageHook(module_keys=('a'))
with pytest.raises(AssertionError):
_ = ExponentialMovingAverageHook(
module_keys=('module_a_ema'), interp_mode='xxx')
# test before run
ema = ExponentialMovingAverageHook(**self.default_config)
self.runner.model = SimpleModelNoEMA()
self.runner.iter = 0
ema.before_run(self.runner)
assert hasattr(self.runner.model, 'module_a_ema')
module_a = self.runner.model.module_a
module_a_ema = self.runner.model.module_a_ema
ema.after_train_iter(self.runner)
ema_states = module_a_ema.state_dict()
assert torch.equal(ema_states['a'], torch.tensor([1., 2.]))
module_a.b /= 2.
module_a.a.data /= 2.
module_a.c /= 2.
self.runner.iter += 1
ema.after_train_iter(self.runner)
ema_states = module_a_ema.state_dict()
assert torch.equal(self.runner.model.module_a.a,
torch.tensor([0.5, 1.]))
assert torch.equal(ema_states['a'], torch.tensor([0.75, 1.5]))
assert torch.equal(ema_states['b'], torch.tensor([1., 1.5]))
assert 'c' not in ema_states
# test ema with simple warm up
runner = SimpleRunner()
cfg_ = deepcopy(self.default_config)
cfg_.update(dict(start_iter=3, interval=1))
ema = ExponentialMovingAverageHook(**cfg_)
ema.before_run(runner)
module_a = runner.model.module_a
module_a_ema = runner.model.module_a_ema
module_a.a.data /= 2.
runner.iter += 1
ema.after_train_iter(runner)
ema_states = module_a_ema.state_dict()
assert torch.equal(runner.model.module_a.a, torch.tensor([0.5, 1.]))
assert torch.equal(ema_states['a'], torch.tensor([0.5, 1.]))
module_a.a.data /= 2
runner.iter += 2
ema.after_train_iter(runner)
ema_states = module_a_ema.state_dict()
assert torch.equal(runner.model.module_a.a, torch.tensor([0.25, 0.5]))
assert torch.equal(ema_states['a'], torch.tensor([0.375, 0.75]))
@pytest.mark.skipif(not torch.cuda.is_available(), reason='requires cuda')
def test_ema_hook_cuda(self):
ema = ExponentialMovingAverageHook(**self.default_config)
cuda_runner = SimpleRunner()
cuda_runner.model = cuda_runner.model.cuda()
ema.after_train_iter(cuda_runner)
module_a = cuda_runner.model.module_a
module_a_ema = cuda_runner.model.module_a_ema
ema_states = module_a_ema.state_dict()
assert torch.equal(ema_states['a'], torch.tensor([1., 2.]).cuda())
module_a.b /= 2.
module_a.a.data /= 2.
module_a.c /= 2.
cuda_runner.iter += 1
ema.after_train_iter(cuda_runner)
ema_states = module_a_ema.state_dict()
assert torch.equal(cuda_runner.model.module_a.a,
torch.tensor([0.5, 1.]).cuda())
assert torch.equal(ema_states['a'], torch.tensor([0.75, 1.5]).cuda())
assert torch.equal(ema_states['b'], torch.tensor([1., 1.5]).cuda())
assert 'c' not in ema_states
# test before run
ema = ExponentialMovingAverageHook(**self.default_config)
self.runner.model = SimpleModelNoEMA().cuda()
self.runner.model = DataParallel(self.runner.model)
self.runner.iter = 0
ema.before_run(self.runner)
assert hasattr(self.runner.model.module, 'module_a_ema')
module_a = self.runner.model.module.module_a
module_a_ema = self.runner.model.module.module_a_ema
ema.after_train_iter(self.runner)
ema_states = module_a_ema.state_dict()
assert torch.equal(ema_states['a'], torch.tensor([1., 2.]).cuda())
module_a.b /= 2.
module_a.a.data /= 2.
module_a.c /= 2.
self.runner.iter += 1
ema.after_train_iter(self.runner)
ema_states = module_a_ema.state_dict()
assert torch.equal(self.runner.model.module.module_a.a,
torch.tensor([0.5, 1.]).cuda())
assert torch.equal(ema_states['a'], torch.tensor([0.75, 1.5]).cuda())
assert torch.equal(ema_states['b'], torch.tensor([1., 1.5]).cuda())
assert 'c' not in ema_states
# test ema with simple warm up
runner = SimpleRunner()
runner.model = runner.model.cuda()
cfg_ = deepcopy(self.default_config)
cfg_.update(dict(start_iter=3, interval=1))
ema = ExponentialMovingAverageHook(**cfg_)
ema.before_run(runner)
module_a = runner.model.module_a
module_a_ema = runner.model.module_a_ema
module_a.a.data /= 2.
runner.iter += 1
ema.after_train_iter(runner)
ema_states = module_a_ema.state_dict()
assert torch.equal(runner.model.module_a.a,
torch.tensor([0.5, 1.]).cuda())
assert torch.equal(ema_states['a'], torch.tensor([0.5, 1.]).cuda())
module_a.a.data /= 2
runner.iter += 2
ema.after_train_iter(runner)
ema_states = module_a_ema.state_dict()
assert torch.equal(runner.model.module_a.a,
torch.tensor([0.25, 0.5]).cuda())
assert torch.equal(ema_states['a'], torch.tensor([0.375, 0.75]).cuda())
| 8,288 | 33.682008 | 79 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_base_model.py | # Copyright (c) OpenMMLab. All rights reserved.
import unittest
from unittest.mock import patch
import pytest
import torch
from mmedit.models import BaseModel
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.randn(5, 5), torch.randn(5, 5)]
b_loss = torch.randn(5, 5)
losses = dict(a_loss=a_loss, b_loss=b_loss)
r_a_loss = sum(_loss.mean() for _loss in a_loss)
r_b_loss = b_loss.mean()
r_loss = [r_a_loss, r_b_loss]
r_loss = sum(r_loss)
loss, log_vars = self.base_model.parse_losses(losses)
assert r_loss == loss
assert set(log_vars.keys()) == set(['a_loss', 'b_loss', 'loss'])
assert log_vars['a_loss'] == r_a_loss
assert log_vars['b_loss'] == r_b_loss
assert log_vars['loss'] == r_loss
| 1,059 | 29.285714 | 72 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_backbones/test_generation_backbones/test_generators.py | # Copyright (c) OpenMMLab. All rights reserved.
import copy
import numpy as np
import pytest
import torch
from mmedit.models import build_backbone
from mmedit.models.common import (ResidualBlockWithDropout,
UnetSkipConnectionBlock)
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)
img = _demo_inputs(input_shape)
# innermost
cfg = copy.deepcopy(_cfg)
cfg['is_innermost'] = True
block = UnetSkipConnectionBlock(**cfg)
# cpu
output = block(feature)
assert output.shape == (1, 2, 8, 8)
# gpu
if torch.cuda.is_available():
block.cuda()
output = block(feature.cuda())
assert output.shape == (1, 2, 8, 8)
block.cpu()
# intermediate
cfg = copy.deepcopy(_cfg)
cfg['submodule'] = block
block = UnetSkipConnectionBlock(**cfg)
# cpu
output = block(feature)
assert output.shape == (1, 2, 8, 8)
# gpu
if torch.cuda.is_available():
block.cuda()
output = block(feature.cuda())
assert output.shape == (1, 2, 8, 8)
block.cpu()
# outermost
cfg = copy.deepcopy(_cfg)
cfg['submodule'] = block
cfg['is_outermost'] = True
cfg['in_channels'] = 3
cfg['outer_channels'] = 3
block = UnetSkipConnectionBlock(**cfg)
# cpu
output = block(img)
assert output.shape == (1, 3, 8, 8)
# gpu
if torch.cuda.is_available():
block.cuda()
output = block(img.cuda())
assert output.shape == (1, 3, 8, 8)
block.cpu()
# test cannot be both innermost and outermost
cfg = copy.deepcopy(_cfg)
cfg['is_innermost'] = True
cfg['is_outermost'] = True
with pytest.raises(AssertionError):
_ = UnetSkipConnectionBlock(**cfg)
# test norm_cfg assertions
bad_cfg = copy.deepcopy(_cfg)
bad_cfg['is_innermost'] = True
bad_cfg['norm_cfg'] = None
with pytest.raises(AssertionError):
_ = UnetSkipConnectionBlock(**bad_cfg)
bad_cfg['norm_cfg'] = dict(tp='BN')
with pytest.raises(AssertionError):
_ = UnetSkipConnectionBlock(**bad_cfg)
def test_unet_generator():
# color to color
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)
# cpu
input_shape = (1, 3, 256, 256)
img = _demo_inputs(input_shape)
output = net(img)
assert output.shape == (1, 3, 256, 256)
# gpu
if torch.cuda.is_available():
net = net.cuda()
output = net(img.cuda())
assert output.shape == (1, 3, 256, 256)
# gray to color
cfg = dict(
type='UnetGenerator',
in_channels=1,
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)
# cpu
input_shape = (1, 1, 256, 256)
img = _demo_inputs(input_shape)
output = net(img)
assert output.shape == (1, 3, 256, 256)
# gpu
if torch.cuda.is_available():
net = net.cuda()
output = net(img.cuda())
assert output.shape == (1, 3, 256, 256)
# color to gray
cfg = dict(
type='UnetGenerator',
in_channels=3,
out_channels=1,
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)
# cpu
input_shape = (1, 3, 256, 256)
img = _demo_inputs(input_shape)
output = net(img)
assert output.shape == (1, 1, 256, 256)
# gpu
if torch.cuda.is_available():
net = net.cuda()
output = net(img.cuda())
assert output.shape == (1, 1, 256, 256)
# pretrained should be str or None
with pytest.raises(TypeError):
net.init_weights(pretrained=[1])
# test norm_cfg assertions
bad_cfg = copy.deepcopy(cfg)
bad_cfg['norm_cfg'] = None
with pytest.raises(AssertionError):
_ = build_backbone(bad_cfg)
bad_cfg['norm_cfg'] = dict(tp='BN')
with pytest.raises(AssertionError):
_ = build_backbone(bad_cfg)
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)
# reflect padding, BN, use_dropout=True
block = ResidualBlockWithDropout(**_cfg)
# cpu
output = block(feature)
assert output.shape == (1, 3, 32, 32)
# gpu
if torch.cuda.is_available():
block = block.cuda()
output = block(feature.cuda())
assert output.shape == (1, 3, 32, 32)
# test other padding types
# replicate padding
cfg = copy.deepcopy(_cfg)
cfg['padding_mode'] = 'replicate'
block = ResidualBlockWithDropout(**cfg)
# cpu
output = block(feature)
assert output.shape == (1, 3, 32, 32)
# gpu
if torch.cuda.is_available():
block = block.cuda()
output = block(feature.cuda())
assert output.shape == (1, 3, 32, 32)
# zero padding
cfg = copy.deepcopy(_cfg)
cfg['padding_mode'] = 'zeros'
block = ResidualBlockWithDropout(**cfg)
# cpu
output = block(feature)
assert output.shape == (1, 3, 32, 32)
# gpu
if torch.cuda.is_available():
block = block.cuda()
output = block(feature.cuda())
assert output.shape == (1, 3, 32, 32)
# not implemented padding
cfg = copy.deepcopy(_cfg)
cfg['padding_mode'] = 'abc'
with pytest.raises(KeyError):
block = ResidualBlockWithDropout(**cfg)
# test other norm
cfg = copy.deepcopy(_cfg)
cfg['norm_cfg'] = dict(type='IN')
block = ResidualBlockWithDropout(**cfg)
# cpu
output = block(feature)
assert output.shape == (1, 3, 32, 32)
# gpu
if torch.cuda.is_available():
block = block.cuda()
output = block(feature.cuda())
assert output.shape == (1, 3, 32, 32)
# test use_dropout=False
cfg = copy.deepcopy(_cfg)
cfg['use_dropout'] = False
block = ResidualBlockWithDropout(**cfg)
# cpu
output = block(feature)
assert output.shape == (1, 3, 32, 32)
# gpu
if torch.cuda.is_available():
block = block.cuda()
output = block(feature.cuda())
assert output.shape == (1, 3, 32, 32)
# test norm_cfg assertions
bad_cfg = copy.deepcopy(_cfg)
bad_cfg['norm_cfg'] = None
with pytest.raises(AssertionError):
_ = ResidualBlockWithDropout(**bad_cfg)
bad_cfg['norm_cfg'] = dict(tp='BN')
with pytest.raises(AssertionError):
_ = ResidualBlockWithDropout(**bad_cfg)
def test_resnet_generator():
# color to color
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)
# cpu
input_shape = (1, 3, 256, 256)
img = _demo_inputs(input_shape)
output = net(img)
assert output.shape == (1, 3, 256, 256)
# gpu
if torch.cuda.is_available():
net = net.cuda()
output = net(img.cuda())
assert output.shape == (1, 3, 256, 256)
# gray to color
cfg = dict(
type='ResnetGenerator',
in_channels=1,
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)
# cpu
input_shape = (1, 1, 256, 256)
img = _demo_inputs(input_shape)
output = net(img)
assert output.shape == (1, 3, 256, 256)
# gpu
if torch.cuda.is_available():
net = net.cuda()
output = net(img.cuda())
assert output.shape == (1, 3, 256, 256)
# color to gray
cfg = dict(
type='ResnetGenerator',
in_channels=3,
out_channels=1,
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)
# cpu
input_shape = (1, 3, 256, 256)
img = _demo_inputs(input_shape)
output = net(img)
assert output.shape == (1, 1, 256, 256)
# gpu
if torch.cuda.is_available():
net = net.cuda()
output = net(img.cuda())
assert output.shape == (1, 1, 256, 256)
# test num_blocks non-negative
bad_cfg = copy.deepcopy(cfg)
bad_cfg['num_blocks'] = -1
with pytest.raises(AssertionError):
net = build_backbone(bad_cfg)
# pretrained should be str or None
with pytest.raises(TypeError):
net.init_weights(pretrained=[1])
# test norm_cfg assertions
bad_cfg = copy.deepcopy(cfg)
bad_cfg['norm_cfg'] = None
with pytest.raises(AssertionError):
_ = build_backbone(bad_cfg)
bad_cfg['norm_cfg'] = dict(tp='IN')
with pytest.raises(AssertionError):
_ = build_backbone(bad_cfg)
def _demo_inputs(input_shape=(1, 3, 64, 64)):
"""Create a superset of inputs needed to run backbone.
Args:
input_shape (tuple): input batch dimensions.
Default: (1, 3, 64, 64).
Returns:
imgs: (Tensor): Images in FloatTensor with desired shapes.
"""
imgs = np.random.random(input_shape)
imgs = torch.FloatTensor(imgs)
return imgs
| 10,368 | 27.17663 | 66 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_backbones/test_sr_backbones/test_real_basicvsr_net.py | # Copyright (c) OpenMMLab. All rights reserved.
import pytest
import torch
from mmedit.models.backbones.sr_backbones.real_basicvsr_net import \
RealBasicVSRNet
def test_real_basicvsr_net():
"""Test RealBasicVSR."""
# cpu
# is_fix_cleaning = False
real_basicvsr = RealBasicVSRNet(is_fix_cleaning=False)
# is_sequential_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_basicvsr(input_tensor)
assert output.shape == (1, 5, 3, 256, 256)
# is_sequential_cleaning = True, return_lq = True
real_basicvsr = RealBasicVSRNet(
is_fix_cleaning=True, is_sequential_cleaning=True)
output, lq = real_basicvsr(input_tensor, return_lqs=True)
assert output.shape == (1, 5, 3, 256, 256)
assert lq.shape == (1, 5, 3, 64, 64)
with pytest.raises(TypeError):
# pretrained should be str or None
real_basicvsr.init_weights(pretrained=[1])
# gpu
if torch.cuda.is_available():
# is_fix_cleaning = False
real_basicvsr = RealBasicVSRNet(is_fix_cleaning=False).cuda()
# is_sequential_cleaning = False
real_basicvsr = RealBasicVSRNet(
is_fix_cleaning=True, is_sequential_cleaning=False).cuda()
input_tensor = torch.rand(1, 5, 3, 64, 64).cuda()
real_basicvsr.init_weights(pretrained=None)
output = real_basicvsr(input_tensor)
assert output.shape == (1, 5, 3, 256, 256)
# is_sequential_cleaning = True, return_lq = True
real_basicvsr = RealBasicVSRNet(
is_fix_cleaning=True, is_sequential_cleaning=True).cuda()
output, lq = real_basicvsr(input_tensor, return_lqs=True)
assert output.shape == (1, 5, 3, 256, 256)
assert lq.shape == (1, 5, 3, 64, 64)
with pytest.raises(TypeError):
# pretrained should be str or None
real_basicvsr.init_weights(pretrained=[1])
| 2,058 | 34.5 | 70 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_backbones/test_sr_backbones/test_sr_backbones.py | # Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
import pytest
import torch
from mmedit.models.backbones import EDSR, SRCNN, MSRResNet, RRDBNet
from mmedit.models.components import ModifiedVGG
def test_srresnet_backbone():
"""Test SRResNet backbone."""
# x2 model
MSRResNet(
in_channels=3,
out_channels=3,
mid_channels=8,
num_blocks=2,
upscale_factor=2)
# x3 model, initialization and forward (cpu)
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, 12)
img = _demo_inputs(input_shape)
output = net(img)
assert output.shape == (1, 3, 36, 36)
# x4 modeland, initialization and forward (cpu)
net = MSRResNet(
in_channels=3,
out_channels=3,
mid_channels=8,
num_blocks=2,
upscale_factor=4)
net.init_weights(pretrained=None)
output = net(img)
assert output.shape == (1, 3, 48, 48)
# x4 model forward (gpu)
if torch.cuda.is_available():
net = net.cuda()
output = net(img.cuda())
assert output.shape == (1, 3, 48, 48)
with pytest.raises(TypeError):
# pretrained should be str or None
net.init_weights(pretrained=[1])
with pytest.raises(ValueError):
# Currently supported upscale_factor is [2, 3, 4]
MSRResNet(
in_channels=3,
out_channels=3,
mid_channels=64,
num_blocks=16,
upscale_factor=16)
def test_edsr():
"""Test EDSR."""
# x2 model
EDSR(
in_channels=3,
out_channels=3,
mid_channels=8,
num_blocks=2,
upscale_factor=2)
# x3 model, initialization and forward (cpu)
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_shape)
output = net(img)
assert output.shape == (1, 3, 36, 36)
# x4 modeland, initialization and forward (cpu)
net = EDSR(
in_channels=3,
out_channels=3,
mid_channels=8,
num_blocks=2,
upscale_factor=4)
net.init_weights(pretrained=None)
output = net(img)
assert output.shape == (1, 3, 48, 48)
# gray x4 modeland, initialization and forward (cpu)
net = EDSR(
in_channels=1,
out_channels=1,
mid_channels=8,
num_blocks=2,
upscale_factor=4,
rgb_mean=[0],
rgb_std=[1])
net.init_weights(pretrained=None)
gray = _demo_inputs((1, 1, 12, 12))
output = net(gray)
assert output.shape == (1, 1, 48, 48)
# x4 model forward (gpu)
if torch.cuda.is_available():
net = net.cuda()
output = net(gray.cuda())
assert output.shape == (1, 1, 48, 48)
with pytest.raises(TypeError):
# pretrained should be str or None
net.init_weights(pretrained=[1])
with pytest.raises(ValueError):
# Currently supported upscale_factor is 2^n and 3
EDSR(
in_channels=3,
out_channels=3,
mid_channels=64,
num_blocks=16,
upscale_factor=5)
def test_discriminator():
"""Test discriminator backbone."""
# model, initialization and forward (cpu)
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)
# model, initialization and forward (gpu)
if torch.cuda.is_available():
net.init_weights(pretrained=None)
net.cuda()
output = net(img.cuda())
assert output.shape == (1, 1)
with pytest.raises(TypeError):
# pretrained should be str or None
net.init_weights(pretrained=[1])
with pytest.raises(AssertionError):
# input size must be 128 * 128
input_shape = (1, 3, 64, 64)
img = _demo_inputs(input_shape)
output = net(img)
def test_rrdbnet_backbone():
"""Test RRDBNet backbone."""
# model, initialization and forward (cpu)
# x4 model
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 output.shape == (1, 3, 48, 48)
# x3 model
with pytest.raises(ValueError):
net = RRDBNet(
in_channels=3,
out_channels=3,
mid_channels=8,
num_blocks=2,
growth_channels=4,
upscale_factor=3)
# x2 model
net = RRDBNet(
in_channels=3,
out_channels=3,
mid_channels=8,
num_blocks=2,
growth_channels=4,
upscale_factor=2)
net.init_weights(pretrained=None)
input_shape = (1, 3, 12, 12)
img = _demo_inputs(input_shape)
output = net(img)
assert output.shape == (1, 3, 24, 24)
# model forward (gpu)
if torch.cuda.is_available():
net = net.cuda()
output = net(img.cuda())
assert output.shape == (1, 3, 24, 24)
with pytest.raises(TypeError):
# pretrained should be str or None
net.init_weights(pretrained=[1])
def test_srcnn():
# model, initialization and forward (cpu)
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_sizes=(3, 3, 3), upscale_factor=2)
net.init_weights(pretrained=None)
input_shape = (1, 1, 4, 4)
img = _demo_inputs(input_shape)
output = net(img)
assert output.shape == (1, 1, 8, 8)
# model forward (gpu)
if torch.cuda.is_available():
net = net.cuda()
output = net(img.cuda())
assert output.shape == (1, 1, 8, 8)
with pytest.raises(AssertionError):
# The length of channel tuple should be 4
net = SRCNN(
channels=(3, 4, 3), kernel_sizes=(9, 1, 5), upscale_factor=4)
with pytest.raises(AssertionError):
# The length of kernel tuple should be 3
net = SRCNN(
channels=(3, 4, 4, 3), kernel_sizes=(9, 1, 1, 5), upscale_factor=4)
with pytest.raises(TypeError):
# pretrained should be str or None
net.init_weights(pretrained=[1])
def _demo_inputs(input_shape=(1, 3, 64, 64)):
"""Create a superset of inputs needed to run backbone.
Args:
input_shape (tuple): input batch dimensions.
Default: (1, 3, 64, 64).
Returns:
imgs: (Tensor): Images in FloatTensor with desired shapes.
"""
imgs = np.random.random(input_shape)
imgs = torch.FloatTensor(imgs)
return imgs
| 7,196 | 26.469466 | 79 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_backbones/test_sr_backbones/test_duf.py | # Copyright (c) OpenMMLab. All rights reserved.
import pytest
import torch
from mmedit.models.backbones.sr_backbones.duf import DynamicUpsamplingFilter
def test_dynamic_upsampling_filter():
"""Test DynamicUpsamplingFilter."""
with pytest.raises(TypeError):
# The type of filter_size must be tuple
DynamicUpsamplingFilter(filter_size=3)
with pytest.raises(ValueError):
# The length of filter size must be 2
DynamicUpsamplingFilter(filter_size=(3, 3, 3))
duf = DynamicUpsamplingFilter(filter_size=(5, 5))
x = torch.rand(1, 3, 4, 4)
filters = torch.rand(1, 25, 16, 4, 4)
output = duf(x, filters)
assert output.shape == (1, 48, 4, 4)
duf = DynamicUpsamplingFilter(filter_size=(3, 3))
x = torch.rand(1, 3, 4, 4)
filters = torch.rand(1, 9, 16, 4, 4)
output = duf(x, filters)
assert output.shape == (1, 48, 4, 4)
# gpu (since it has dcn, only supports gpu testing)
if torch.cuda.is_available():
duf = DynamicUpsamplingFilter(filter_size=(3, 3)).cuda()
x = torch.rand(1, 3, 4, 4).cuda()
filters = torch.rand(1, 9, 16, 4, 4).cuda()
output = duf(x, filters)
assert output.shape == (1, 48, 4, 4)
| 1,223 | 33 | 76 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_backbones/test_sr_backbones/test_liif_net.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch
from mmedit.models import build_backbone
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)
# build model
model = build_backbone(model_cfg)
# test attributes
assert model.__class__.__name__ == 'LIIFEDSR'
# prepare data
inputs = torch.rand(1, 3, 22, 11)
targets = torch.rand(1, 128 * 64, 3)
coord = torch.rand(1, 128 * 64, 2)
cell = torch.rand(1, 128 * 64, 2)
# test on cpu
output = model(inputs, coord, cell)
output = model(inputs, coord, cell, True)
assert torch.is_tensor(output)
assert output.shape == targets.shape
# test on gpu
if torch.cuda.is_available():
model = model.cuda()
inputs = inputs.cuda()
targets = targets.cuda()
coord = coord.cuda()
cell = cell.cuda()
output = model(inputs, coord, cell)
output = model(inputs, coord, cell, True)
assert torch.is_tensor(output)
assert output.shape == targets.shape
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=True,
cell_decode=True,
eval_bsize=30000)
# build model
model = build_backbone(model_cfg)
# test attributes
assert model.__class__.__name__ == 'LIIFRDN'
# prepare data
inputs = torch.rand(1, 3, 22, 11)
targets = torch.rand(1, 128 * 64, 3)
coord = torch.rand(1, 128 * 64, 2)
cell = torch.rand(1, 128 * 64, 2)
# test on cpu
output = model(inputs, coord, cell)
output = model(inputs, coord, cell, True)
assert torch.is_tensor(output)
assert output.shape == targets.shape
# test on gpu
if torch.cuda.is_available():
model = model.cuda()
inputs = inputs.cuda()
targets = targets.cuda()
coord = coord.cuda()
cell = cell.cuda()
output = model(inputs, coord, cell)
output = model(inputs, coord, cell, True)
assert torch.is_tensor(output)
assert output.shape == targets.shape
| 2,884 | 25.227273 | 49 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_backbones/test_sr_backbones/test_iconvsr.py | # Copyright (c) OpenMMLab. All rights reserved.
import pytest
import torch
from mmedit.models.backbones.sr_backbones.iconvsr import IconVSR
def test_iconvsr():
"""Test IconVSR."""
# gpu (since IconVSR contains DCN, only GPU mode is available)
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)
output = iconvsr(input_tensor)
assert output.shape == (1, 5, 3, 256, 256)
with pytest.raises(AssertionError):
# The height and width of inputs should be at least 64
input_tensor = torch.rand(1, 5, 3, 61, 61)
iconvsr(input_tensor)
with pytest.raises(TypeError):
# pretrained should be str or None
iconvsr.init_weights(pretrained=[1])
# spynet_pretrained should be str or None
with pytest.raises(TypeError):
iconvsr = IconVSR(
mid_channels=64,
num_blocks=30,
keyframe_stride=5,
padding=2,
spynet_pretrained=123,
edvr_pretrained=None).cuda()
# edvr_pretrained should be str or None
with pytest.raises(TypeError):
iconvsr = IconVSR(
mid_channels=64,
num_blocks=30,
keyframe_stride=5,
padding=2,
spynet_pretrained=None,
edvr_pretrained=123).cuda()
| 1,695 | 30.407407 | 66 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_backbones/test_sr_backbones/test_tdan_net.py | # Copyright (c) OpenMMLab. All rights reserved.
import pytest
import torch
from mmedit.models.backbones.sr_backbones.tdan_net import TDANNet
def test_tdan_net():
"""Test TDANNet."""
# gpu (DCN is available only on GPU)
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 # (1) HR center + (2) aligned LRs
assert output[0].shape == (1, 3, 256, 256) # HR center frame
assert output[1].shape == (1, 5, 3, 64, 64) # aligned LRs
with pytest.raises(TypeError):
# pretrained should be str or None
tdan.init_weights(pretrained=[1])
| 772 | 29.92 | 69 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_backbones/test_sr_backbones/test_basicvsr_net.py | # Copyright (c) OpenMMLab. All rights reserved.
import pytest
import torch
from mmedit.models.backbones.sr_backbones.basicvsr_net import BasicVSRNet
def test_basicvsr_net():
"""Test BasicVSR."""
# cpu
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)
# gpu
if torch.cuda.is_available():
basicvsr = BasicVSRNet(
mid_channels=64, num_blocks=30, spynet_pretrained=None).cuda()
input_tensor = torch.rand(1, 5, 3, 64, 64).cuda()
basicvsr.init_weights(pretrained=None)
output = basicvsr(input_tensor)
assert output.shape == (1, 5, 3, 256, 256)
with pytest.raises(AssertionError):
# The height and width of inputs should be at least 64
input_tensor = torch.rand(1, 5, 3, 61, 61)
basicvsr(input_tensor)
with pytest.raises(TypeError):
# pretrained should be str or None
basicvsr.init_weights(pretrained=[1])
| 1,137 | 30.611111 | 74 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_backbones/test_sr_backbones/test_dic_net.py | # Copyright (c) OpenMMLab. All rights reserved.
import pytest
import torch
import torch.nn as nn
from mmedit.models import build_backbone
from mmedit.models.backbones.sr_backbones.dic_net import (
FeedbackBlock, FeedbackBlockCustom, FeedbackBlockHeatmapAttention)
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)
# build model
model = build_backbone(model_cfg)
# test attributes
assert model.__class__.__name__ == 'DICNet'
# prepare data
inputs = torch.rand(1, 3, 16, 16)
targets = torch.rand(1, 3, 128, 128)
# prepare loss
loss_function = nn.L1Loss()
# prepare optimizer
optimizer = torch.optim.Adam(model.parameters())
# test on cpu
output, _ = model(inputs)
optimizer.zero_grad()
loss = loss_function(output[-1], targets)
loss.backward()
optimizer.step()
assert len(output) == 4
assert torch.is_tensor(output[-1])
assert output[-1].shape == targets.shape
# test on gpu
if torch.cuda.is_available():
model = model.cuda()
optimizer = torch.optim.Adam(model.parameters())
inputs = inputs.cuda()
targets = targets.cuda()
output, _ = model(inputs)
optimizer.zero_grad()
loss = loss_function(output[-1], targets)
loss.backward()
optimizer.step()
assert len(output) == 4
assert torch.is_tensor(output[-1])
assert output[-1].shape == targets.shape
with pytest.raises(OSError):
model.init_weights('')
with pytest.raises(TypeError):
model.init_weights(1)
| 2,496 | 24.222222 | 70 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_backbones/test_sr_backbones/test_glean_net.py | # Copyright (c) OpenMMLab. All rights reserved.
import pytest
import torch
from mmedit.models.backbones.sr_backbones.glean_styleganv2 import \
GLEANStyleGANv2
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):
# test default config
glean = GLEANStyleGANv2(**self.default_cfg)
img = torch.randn(2, 3, 16, 16)
res = glean(img)
assert res.shape == (2, 3, 256, 256)
with pytest.raises(TypeError):
# pretrained should be str or None
glean.init_weights(pretrained=[1])
# input tensor size must equal self.in_size
with pytest.raises(AssertionError):
res = glean(torch.randn(2, 3, 17, 32))
# input size must be strictly smaller than output size
with pytest.raises(ValueError):
glean = GLEANStyleGANv2(**self.size_cfg)
@pytest.mark.skipif(not torch.cuda.is_available(), reason='requires cuda')
def test_glean_styleganv2_cuda(self):
# test default config
glean = GLEANStyleGANv2(**self.default_cfg).cuda()
img = torch.randn(2, 3, 16, 16).cuda()
res = glean(img)
assert res.shape == (2, 3, 256, 256)
with pytest.raises(TypeError):
# pretrained should be str or None
glean.init_weights(pretrained=[1])
# input tensor size must equal self.in_size
with pytest.raises(AssertionError):
res = glean(torch.randn(2, 3, 32, 17).cuda())
# input size must be strictly smaller than output size
with pytest.raises(ValueError):
glean = GLEANStyleGANv2(**self.size_cfg).cuda()
| 1,834 | 32.981481 | 78 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_backbones/test_sr_backbones/test_edvr_net.py | # Copyright (c) OpenMMLab. All rights reserved.
import pytest
import torch
from mmedit.models.backbones.sr_backbones.edvr_net import (EDVRNet,
PCDAlignment,
TSAFusion)
def test_pcd_alignment():
"""Test PCDAlignment."""
# cpu
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]
output = pcd_alignment(input_list, input_list)
assert output.shape == (1, 4, 8, 8)
with pytest.raises(AssertionError):
pcd_alignment(input_list[0:2], input_list)
# gpu
if torch.cuda.is_available():
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.cuda()
input_list = [v.cuda() for v in input_list]
output = pcd_alignment(input_list, input_list)
assert output.shape == (1, 4, 8, 8)
with pytest.raises(AssertionError):
pcd_alignment(input_list[0:2], input_list)
def test_tsa_fusion():
"""Test TSAFusion."""
# cpu
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)
# gpu
if torch.cuda.is_available():
tsa_fusion = tsa_fusion.cuda()
input_tensor = input_tensor.cuda()
output = tsa_fusion(input_tensor)
assert output.shape == (1, 4, 8, 8)
def test_edvrnet():
"""Test EDVRNet."""
# cpu
# with tsa
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_tensor)
assert output.shape == (1, 3, 32, 32)
# without tsa
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=False)
output = edvrnet(input_tensor)
assert output.shape == (1, 3, 32, 32)
with pytest.raises(AssertionError):
# The height and width of inputs should be a multiple of 4
input_tensor = torch.rand(1, 5, 3, 3, 3)
edvrnet(input_tensor)
with pytest.raises(TypeError):
# pretrained should be str or None
edvrnet.init_weights(pretrained=[1])
# gpu
if torch.cuda.is_available():
# with tsa
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).cuda()
input_tensor = torch.rand(1, 5, 3, 8, 8).cuda()
edvrnet.init_weights(pretrained=None)
output = edvrnet(input_tensor)
assert output.shape == (1, 3, 32, 32)
# without tsa
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=False).cuda()
output = edvrnet(input_tensor)
assert output.shape == (1, 3, 32, 32)
with pytest.raises(AssertionError):
# The height and width of inputs should be a multiple of 4
input_tensor = torch.rand(1, 5, 3, 3, 3).cuda()
edvrnet(input_tensor)
with pytest.raises(TypeError):
# pretrained should be str or None
edvrnet.init_weights(pretrained=[1])
| 4,187 | 27.489796 | 76 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_backbones/test_sr_backbones/test_tof.py | # Copyright (c) OpenMMLab. All rights reserved.
import pytest
import torch
from mmedit.models.backbones import TOFlow
def test_tof():
"""Test TOFlow."""
# cpu
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(pretrained=None)
output = tof(input_tensor)
assert output.shape == (1, 3, 32, 32)
with pytest.raises(TypeError):
# pretrained should be str or None
tof.init_weights(pretrained=[1])
# gpu
if torch.cuda.is_available():
tof = TOFlow(adapt_official_weights=True).cuda()
input_tensor = torch.rand(1, 7, 3, 32, 32).cuda()
tof.init_weights(pretrained=None)
output = tof(input_tensor)
assert output.shape == (1, 3, 32, 32)
| 937 | 26.588235 | 57 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_backbones/test_sr_backbones/test_rdn.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch
import torch.nn as nn
from mmedit.models import build_backbone
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)
# build model
model = build_backbone(model_cfg)
# test attributes
assert model.__class__.__name__ == 'RDN'
# prepare data
inputs = torch.rand(1, 3, 32, 16)
targets = torch.rand(1, 3, 128, 64)
# prepare loss
loss_function = nn.L1Loss()
# prepare optimizer
optimizer = torch.optim.Adam(model.parameters())
# test on cpu
output = model(inputs)
optimizer.zero_grad()
loss = loss_function(output, targets)
loss.backward()
optimizer.step()
assert torch.is_tensor(output)
assert output.shape == targets.shape
# test on gpu
if torch.cuda.is_available():
model = model.cuda()
optimizer = torch.optim.Adam(model.parameters())
inputs = inputs.cuda()
targets = targets.cuda()
output = model(inputs)
optimizer.zero_grad()
loss = loss_function(output, targets)
loss.backward()
optimizer.step()
assert torch.is_tensor(output)
assert output.shape == targets.shape
| 1,353 | 22.344828 | 56 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_backbones/test_sr_backbones/test_basicvsr_plusplus.py | # Copyright (c) OpenMMLab. All rights reserved.
import pytest
import torch
from mmedit.models.backbones.sr_backbones.basicvsr_pp import BasicVSRPlusPlus
def test_basicvsr_plusplus():
"""Test BasicVSR++."""
# cpu
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 output.shape == (1, 5, 3, 256, 256)
# with cpu_cache (no effect on cpu)
model = BasicVSRPlusPlus(
mid_channels=64,
num_blocks=7,
is_low_res_input=True,
spynet_pretrained=None,
cpu_cache_length=3)
output = model(input_tensor)
assert output.shape == (1, 5, 3, 256, 256)
with pytest.raises(AssertionError):
# The height and width of inputs should be at least 64
input_tensor = torch.rand(1, 5, 3, 61, 61)
model(input_tensor)
with pytest.raises(TypeError):
# pretrained should be str or None
model.init_weights(pretrained=[1])
# output has the same size as input
model = BasicVSRPlusPlus(
mid_channels=64,
num_blocks=7,
is_low_res_input=False,
spynet_pretrained=None,
cpu_cache_length=100)
input_tensor = torch.rand(1, 5, 3, 256, 256)
output = model(input_tensor)
assert output.shape == (1, 5, 3, 256, 256)
# gpu
if torch.cuda.is_available():
model = BasicVSRPlusPlus(
mid_channels=64,
num_blocks=7,
is_low_res_input=True,
spynet_pretrained=None,
cpu_cache_length=100).cuda()
input_tensor = torch.rand(1, 5, 3, 64, 64).cuda()
model.init_weights(pretrained=None)
output = model(input_tensor)
assert output.shape == (1, 5, 3, 256, 256)
# with cpu_cache
model = BasicVSRPlusPlus(
mid_channels=64,
num_blocks=7,
is_low_res_input=True,
spynet_pretrained=None,
cpu_cache_length=3).cuda()
output = model(input_tensor)
assert output.shape == (1, 5, 3, 256, 256)
with pytest.raises(AssertionError):
# The height and width of inputs should be at least 64
input_tensor = torch.rand(1, 5, 3, 61, 61).cuda()
model(input_tensor)
with pytest.raises(TypeError):
# pretrained should be str or None
model.init_weights(pretrained=[1]).cuda()
# output has the same size as input
model = BasicVSRPlusPlus(
mid_channels=64,
num_blocks=7,
is_low_res_input=False,
spynet_pretrained=None,
cpu_cache_length=100).cuda()
input_tensor = torch.rand(1, 5, 3, 256, 256).cuda()
output = model(input_tensor)
assert output.shape == (1, 5, 3, 256, 256)
| 2,987 | 30.452632 | 77 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_backbones/test_vfi_backbones/test_cain_net.py | # Copyright (c) OpenMMLab. All rights reserved.
import pytest
import torch
from mmedit.models import build_backbone
def test_cain_net():
model_cfg = dict(type='CAINNet')
# build model
model = build_backbone(model_cfg)
# test attributes
assert model.__class__.__name__ == 'CAINNet'
# prepare data
inputs0 = torch.rand(1, 2, 3, 5, 5)
target0 = torch.rand(1, 3, 5, 5)
inputs = torch.rand(1, 2, 3, 256, 248)
target = torch.rand(1, 3, 256, 248)
# test on cpu
output = model(inputs)
output = model(inputs, padding_flag=True)
model(inputs0, padding_flag=True)
assert torch.is_tensor(output)
assert output.shape == target.shape
with pytest.raises(AssertionError):
output = model(inputs[:, :1])
with pytest.raises(OSError):
model.init_weights('')
with pytest.raises(TypeError):
model.init_weights(1)
model_cfg = dict(type='CAINNet', norm='in')
model = build_backbone(model_cfg)
model(inputs)
model_cfg = dict(type='CAINNet', norm='bn')
model = build_backbone(model_cfg)
model(inputs)
with pytest.raises(ValueError):
model_cfg = dict(type='CAINNet', norm='lys')
build_backbone(model_cfg)
# test on gpu
if torch.cuda.is_available():
model = model.cuda()
inputs = inputs.cuda()
target = target.cuda()
output = model(inputs)
output = model(inputs, True)
assert torch.is_tensor(output)
assert output.shape == target.shape
inputs0 = inputs0.cuda()
target0 = target0.cuda()
model(inputs0, padding_flag=True)
model_cfg = dict(type='CAINNet', norm='in')
model = build_backbone(model_cfg).cuda()
model(inputs)
model_cfg = dict(type='CAINNet', norm='bn')
model = build_backbone(model_cfg).cuda()
model(inputs)
with pytest.raises(ValueError):
model_cfg = dict(type='CAINNet', norm='lys')
build_backbone(model_cfg).cuda()
| 2,023 | 28.333333 | 56 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_backbones/test_vfi_backbones/test_tof_vfi_net.py | # Copyright (c) OpenMMLab. All rights reserved.
import pytest
import torch
from mmedit.models import build_backbone
def test_tof_vfi_net():
model_cfg = dict(type='TOFlowVFINet')
# build model
model = build_backbone(model_cfg)
# test attributes
assert model.__class__.__name__ == 'TOFlowVFINet'
# prepare data
inputs = torch.rand(1, 2, 3, 256, 248)
# test on cpu
output = model(inputs)
assert torch.is_tensor(output)
assert output.shape == (1, 3, 256, 248)
# test on gpu
if torch.cuda.is_available():
model = model.cuda()
inputs = inputs.cuda()
output = model(inputs)
output = model(inputs, True)
assert torch.is_tensor(output)
assert output.shape == (1, 3, 256, 256)
inputs = torch.rand(1, 2, 3, 256, 256)
output = model(inputs)
assert torch.is_tensor(output)
with pytest.raises(OSError):
model.init_weights('')
with pytest.raises(TypeError):
model.init_weights(1)
with pytest.raises(OSError):
model_cfg = dict(
type='TOFlowVFINet', flow_cfg=dict(norm_cfg=None, pretrained=''))
model = build_backbone(model_cfg)
with pytest.raises(TypeError):
model_cfg = dict(
type='TOFlowVFINet', flow_cfg=dict(norm_cfg=None, pretrained=1))
model = build_backbone(model_cfg)
| 1,371 | 25.901961 | 77 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_backbones/test_encoder_decoders/test_gl_model.py | # Copyright (c) OpenMMLab. All rights reserved.
import pytest
import torch
from mmedit.models import build_backbone, build_component
from mmedit.models.backbones import GLDilationNeck
from mmedit.models.common import SimpleGatedConvModule
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'] = dict(type='GLDecoder', out_act='sigmoid')
gl_encdec = build_backbone(cfg_)
output = gl_encdec(input_x)
assert output.shape == (1, 3, 256, 256)
with pytest.raises(ValueError):
cfg_ = template_cfg.copy()
cfg_['decoder'] = dict(type='GLDecoder', out_act='igccc')
gl_encdec = build_backbone(cfg_)
with pytest.raises(TypeError):
gl_encdec.init_weights(pretrained=dict(igccc=4396))
if torch.cuda.is_available():
gl_encdec = build_backbone(template_cfg)
gl_encdec.init_weights()
gl_encdec = gl_encdec.cuda()
output = gl_encdec(input_x.cuda())
assert output.shape == (1, 3, 256, 256)
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)
assert res.shape == (2, 8, 64, 64)
neck = GLDilationNeck(in_channels=8, conv_type='gated_conv').cuda()
res = neck(x)
assert isinstance(neck.dilation_convs[0], SimpleGatedConvModule)
assert res.shape == (2, 8, 64, 64)
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='BN'))
gl_disc_cfg = dict(
type='GLDiscs',
global_disc_cfg=global_disc_cfg,
local_disc_cfg=local_disc_cfg)
gl_discs = build_component(gl_disc_cfg)
gl_discs.init_weights()
input_g = torch.randn(1, 3, 256, 256)
input_l = torch.randn(1, 3, 128, 128)
output = gl_discs((input_g, input_l))
assert output.shape == (1, 1)
with pytest.raises(TypeError):
gl_discs.init_weights(pretrained=dict(igccc=777))
if torch.cuda.is_available():
gl_discs = gl_discs.cuda()
input_g = torch.randn(1, 3, 256, 256).cuda()
input_l = torch.randn(1, 3, 128, 128).cuda()
output = gl_discs((input_g, input_l))
assert output.shape == (1, 1)
| 2,945 | 30.010526 | 75 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_backbones/test_encoder_decoders/test_deepfill_encoder.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch
from mmedit.models.backbones import ContextualAttentionNeck, DeepFillEncoder
from mmedit.models.common import SimpleGatedConvModule
def test_deepfill_enc():
encoder = DeepFillEncoder()
x = torch.randn((2, 5, 256, 256))
outputs = encoder(x)
assert isinstance(outputs, dict)
assert 'out' in outputs
res = outputs['out']
assert res.shape == (2, 128, 64, 64)
assert encoder.enc2.stride == (2, 2)
assert encoder.enc2.out_channels == 64
encoder = DeepFillEncoder(encoder_type='stage2_conv')
x = torch.randn((2, 5, 256, 256))
outputs = encoder(x)
assert isinstance(outputs, dict)
assert 'out' in outputs
res = outputs['out']
assert res.shape == (2, 128, 64, 64)
assert encoder.enc2.out_channels == 32
assert encoder.enc3.out_channels == 64
assert encoder.enc4.out_channels == 64
encoder = DeepFillEncoder(encoder_type='stage2_attention')
x = torch.randn((2, 5, 256, 256))
outputs = encoder(x)
assert isinstance(outputs, dict)
assert 'out' in outputs
res = outputs['out']
assert res.shape == (2, 128, 64, 64)
assert encoder.enc2.out_channels == 32
assert encoder.enc3.out_channels == 64
assert encoder.enc4.out_channels == 128
if torch.cuda.is_available():
encoder = DeepFillEncoder().cuda()
x = torch.randn((2, 5, 256, 256)).cuda()
outputs = encoder(x)
assert isinstance(outputs, dict)
assert 'out' in outputs
res = outputs['out']
assert res.shape == (2, 128, 64, 64)
assert encoder.enc2.stride == (2, 2)
assert encoder.enc2.out_channels == 64
encoder = DeepFillEncoder(encoder_type='stage2_conv').cuda()
x = torch.randn((2, 5, 256, 256)).cuda()
outputs = encoder(x)
assert isinstance(outputs, dict)
assert 'out' in outputs
res = outputs['out']
assert res.shape == (2, 128, 64, 64)
assert encoder.enc2.out_channels == 32
assert encoder.enc3.out_channels == 64
assert encoder.enc4.out_channels == 64
encoder = DeepFillEncoder(encoder_type='stage2_attention').cuda()
x = torch.randn((2, 5, 256, 256)).cuda()
outputs = encoder(x)
assert isinstance(outputs, dict)
assert 'out' in outputs
res = outputs['out']
assert res.shape == (2, 128, 64, 64)
assert encoder.enc2.out_channels == 32
assert encoder.enc3.out_channels == 64
assert encoder.enc4.out_channels == 128
encoder = DeepFillEncoder(
conv_type='gated_conv', channel_factor=0.75).cuda()
x = torch.randn((2, 5, 256, 256)).cuda()
outputs = encoder(x)
assert isinstance(outputs, dict)
assert 'out' in outputs
res = outputs['out']
assert res.shape == (2, 96, 64, 64)
assert isinstance(encoder.enc2, SimpleGatedConvModule)
assert encoder.enc2.conv.stride == (2, 2)
assert encoder.enc2.conv.out_channels == 48 * 2
def test_deepfill_contextual_attention_neck():
# TODO: add unittest for contextual attention module
neck = ContextualAttentionNeck(in_channels=128)
x = torch.rand((2, 128, 64, 64))
mask = torch.zeros((2, 1, 64, 64))
mask[..., 20:100, 23:90] = 1.
res, offset = neck(x, mask)
assert res.shape == (2, 128, 64, 64)
assert offset.shape == (2, 32, 32, 32, 32)
if torch.cuda.is_available():
neck.cuda()
res, offset = neck(x.cuda(), mask.cuda())
assert res.shape == (2, 128, 64, 64)
assert offset.shape == (2, 32, 32, 32, 32)
neck = ContextualAttentionNeck(
in_channels=128, conv_type='gated_conv').cuda()
res, offset = neck(x.cuda(), mask.cuda())
assert res.shape == (2, 128, 64, 64)
assert offset.shape == (2, 32, 32, 32, 32)
assert isinstance(neck.conv1, SimpleGatedConvModule)
| 3,966 | 34.738739 | 76 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_backbones/test_encoder_decoders/test_aot_model.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch
from mmedit.models import build_backbone
from mmedit.models.backbones.encoder_decoders.necks import AOTBlockNeck
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'] = dict(type='AOTEncoder')
aot_encdec = build_backbone(cfg_)
output = aot_encdec(input_x)
assert output.shape == (1, 3, 256, 256)
cfg_ = template_cfg.copy()
cfg_['decoder'] = dict(type='AOTDecoder')
aot_encdec = build_backbone(cfg_)
output = aot_encdec(input_x)
assert output.shape == (1, 3, 256, 256)
if torch.cuda.is_available():
aot_encdec = build_backbone(template_cfg)
aot_encdec.init_weights()
aot_encdec = aot_encdec.cuda()
output = aot_encdec(input_x.cuda())
assert output.shape == (1, 3, 256, 256)
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, 8),
num_aotblock=8).cuda()
x = torch.rand((2, 256, 64, 64)).cuda()
res = neck(x)
assert res.shape == (2, 256, 64, 64)
| 1,576 | 29.921569 | 71 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_backbones/test_encoder_decoders/test_deepfill_decoder.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch
from mmedit.models.backbones import DeepFillDecoder
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.dec2.stride == (1, 1)
assert decoder.dec2.out_channels == 128
assert not decoder.dec7.with_activation
assert res.min().item() >= -1. and res.max().item() <= 1
if torch.cuda.is_available():
decoder = DeepFillDecoder(128).cuda()
x = torch.randn((2, 128, 64, 64)).cuda()
input_dict = dict(out=x)
res = decoder(input_dict)
assert res.shape == (2, 3, 256, 256)
assert decoder.dec2.stride == (1, 1)
assert decoder.dec2.out_channels == 128
assert not decoder.dec7.with_activation
assert res.min().item() >= -1. and res.max().item() <= 1
decoder = DeepFillDecoder(
128, conv_type='gated_conv', channel_factor=0.75).cuda()
x = torch.randn((2, 128, 64, 64)).cuda()
input_dict = dict(out=x)
res = decoder(input_dict)
assert res.shape == (2, 3, 256, 256)
assert decoder.dec2.conv.stride == (1, 1)
assert decoder.dec2.conv.out_channels == 96 * 2
assert not decoder.dec7.with_feat_act
assert res.min().item() >= -1. and res.max().item() <= 1
| 1,533 | 34.674419 | 68 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_backbones/test_encoder_decoders/test_decoders.py | # Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
import pytest
import torch
from mmedit.models.backbones import (VGG16, FBADecoder, IndexedUpsample,
IndexNetDecoder, IndexNetEncoder,
PlainDecoder, ResGCADecoder,
ResGCAEncoder, ResNetDec, ResNetEnc,
ResShortcutDec, ResShortcutEnc)
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)):
"""
Create a superset of inputs needed to run encoder.
Args:
input_shape (tuple): input batch dimensions.
Default: (1, 4, 64, 64).
"""
img = np.random.random(input_shape).astype(np.float32)
img = torch.from_numpy(img)
return img
def test_plain_decoder():
"""Test PlainDecoder."""
model = PlainDecoder(512)
model.init_weights()
model.train()
# create max_pooling index for training
encoder = VGG16(4)
img = _demo_inputs()
outputs = encoder(img)
prediction = model(outputs)
assert_tensor_with_shape(prediction, torch.Size([1, 1, 64, 64]))
# test forward with gpu
if torch.cuda.is_available():
model = PlainDecoder(512)
model.init_weights()
model.train()
model.cuda()
encoder = VGG16(4)
encoder.cuda()
img = _demo_inputs().cuda()
outputs = encoder(img)
prediction = model(outputs)
assert_tensor_with_shape(prediction, torch.Size([1, 1, 64, 64]))
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], 6)
img = _demo_inputs((1, 6, 64, 64))
feat = encoder(img)
prediction = model(feat)
assert_tensor_with_shape(prediction, torch.Size([1, 1, 64, 64]))
model = ResNetDec(
'BasicBlockDec', [2, 3, 3, 2], 512, with_spectral_norm=True)
assert hasattr(model.conv1.conv, 'weight_orig')
model.init_weights()
model.train()
encoder = ResNetEnc('BasicBlock', [2, 4, 4, 2], 6)
img = _demo_inputs((1, 6, 64, 64))
feat = encoder(img)
prediction = model(feat)
assert_tensor_with_shape(prediction, torch.Size([1, 1, 64, 64]))
# test forward with gpu
if torch.cuda.is_available():
model = ResNetDec('BasicBlockDec', [2, 3, 3, 2], 512, kernel_size=5)
model.init_weights()
model.train()
model.cuda()
encoder = ResNetEnc('BasicBlock', [2, 4, 4, 2], 6)
encoder.cuda()
img = _demo_inputs((1, 6, 64, 64)).cuda()
feat = encoder(img)
prediction = model(feat)
assert_tensor_with_shape(prediction, torch.Size([1, 1, 64, 64]))
model = ResNetDec(
'BasicBlockDec', [2, 3, 3, 2], 512, with_spectral_norm=True)
assert hasattr(model.conv1.conv, 'weight_orig')
model.init_weights()
model.train()
model.cuda()
encoder = ResNetEnc('BasicBlock', [2, 4, 4, 2], 6)
encoder.cuda()
img = _demo_inputs((1, 6, 64, 64)).cuda()
feat = encoder(img)
prediction = model(feat)
assert_tensor_with_shape(prediction, torch.Size([1, 1, 64, 64]))
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('BasicBlock', [2, 4, 4, 2], 6)
img = _demo_inputs((1, 6, 64, 64))
outputs = encoder(img)
prediction = model(outputs)
assert_tensor_with_shape(prediction, torch.Size([1, 1, 64, 64]))
# test forward with gpu
if torch.cuda.is_available():
model = ResShortcutDec('BasicBlockDec', [2, 3, 3, 2], 512)
model.init_weights()
model.train()
model.cuda()
encoder = ResShortcutEnc('BasicBlock', [2, 4, 4, 2], 6)
encoder.cuda()
img = _demo_inputs((1, 6, 64, 64)).cuda()
outputs = encoder(img)
prediction = model(outputs)
assert_tensor_with_shape(prediction, torch.Size([1, 1, 64, 64]))
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 = ResGCAEncoder('BasicBlock', [2, 4, 4, 2], 6)
img = _demo_inputs((2, 6, 32, 32))
outputs = encoder(img)
prediction = model(outputs)
assert_tensor_with_shape(prediction, torch.Size([2, 1, 32, 32]))
# test forward with gpu
if torch.cuda.is_available():
model = ResGCADecoder('BasicBlockDec', [2, 3, 3, 2], 512)
model.init_weights()
model.train()
model.cuda()
encoder = ResGCAEncoder('BasicBlock', [2, 4, 4, 2], 6)
encoder.cuda()
img = _demo_inputs((2, 6, 32, 32)).cuda()
outputs = encoder(img)
prediction = model(outputs)
assert_tensor_with_shape(prediction, torch.Size([2, 1, 32, 32]))
def test_indexed_upsample():
"""Test indexed upsample module for indexnet decoder."""
indexed_upsample = IndexedUpsample(12, 12)
# test indexed_upsample without dec_idx_feat (no upsample)
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))
# test indexed_upsample without dec_idx_feat (with upsample)
x = torch.rand(2, 6, 32, 32)
dec_idx_feat = torch.rand(2, 6, 64, 64)
shortcut = torch.rand(2, 6, 64, 64)
output = indexed_upsample(x, shortcut, dec_idx_feat)
assert_tensor_with_shape(output, (2, 12, 64, 64))
def test_indexnet_decoder():
"""Test Indexnet decoder."""
# test indexnet decoder with default indexnet setting
with pytest.raises(AssertionError):
# shortcut must have four dimensions
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)
outputs_enc = dict(
out=x, shortcuts=[shortcut], dec_idx_feat_list=[dec_idx_feat])
indexnet_decoder(outputs_enc)
indexnet_decoder = IndexNetDecoder(
160, kernel_size=5, separable_conv=False)
indexnet_decoder.init_weights()
indexnet_encoder = IndexNetEncoder(4)
x = torch.rand(2, 4, 32, 32)
outputs_enc = indexnet_encoder(x)
out = indexnet_decoder(outputs_enc)
assert out.shape == (2, 1, 32, 32)
# test indexnet decoder with other setting
indexnet_decoder = IndexNetDecoder(160, kernel_size=3, separable_conv=True)
indexnet_decoder.init_weights()
out = indexnet_decoder(outputs_enc)
assert out.shape == (2, 1, 32, 32)
def test_fba_decoder():
with pytest.raises(AssertionError):
# pool_scales must be list|tuple
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_inputs((1, 512, 40, 40))
conv_out_5 = _demo_inputs((1, 1024, 40, 40))
conv_out_6 = _demo_inputs((1, 2048, 40, 40))
inputs['conv_out'] = [
conv_out_1, conv_out_2, conv_out_3, conv_out_4, conv_out_5, conv_out_6
]
inputs['merged'] = _demo_inputs((1, 3, 320, 320))
inputs['two_channel_trimap'] = _demo_inputs((1, 2, 320, 320))
model = FBADecoder(
pool_scales=(1, 2, 3, 6),
in_channels=2048,
channels=256,
norm_cfg=dict(type='GN', num_groups=32))
alpha, F, B = model(inputs)
assert_tensor_with_shape(alpha, torch.Size([1, 1, 320, 320]))
assert_tensor_with_shape(F, torch.Size([1, 3, 320, 320]))
assert_tensor_with_shape(B, torch.Size([1, 3, 320, 320]))
| 8,503 | 33.710204 | 79 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_backbones/test_encoder_decoders/test_encoder_decoder.py | # Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
import torch
from mmedit.models.backbones import SimpleEncoderDecoder
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."""
# check DIM with only alpha loss
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 = model(torch.cat([merged, trimap], 1))
assert_tensor_with_shape(prediction, torch.Size([1, 1, 64, 64]))
# check DIM with only composition loss
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 = model(torch.cat([merged, trimap], 1))
assert_tensor_with_shape(prediction, torch.Size([1, 1, 64, 64]))
# check DIM with both alpha and composition loss
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 = model(torch.cat([merged, trimap], 1))
assert_tensor_with_shape(prediction, torch.Size([1, 1, 64, 64]))
# test forward with gpu
if torch.cuda.is_available():
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(cuda=True)
model.cuda()
prediction = model(torch.cat([merged, trimap], 1))
assert_tensor_with_shape(prediction, torch.Size([1, 1, 64, 64]))
def _demo_inputs_pair(img_shape=(64, 64), batch_size=1, cuda=False):
"""
Create a superset of inputs needed to run backbone.
Args:
img_shape (tuple): shape of the input image.
batch_size (int): batch size of the input batch.
cuda (bool): whether transfer input into gpu.
"""
color_shape = (batch_size, 3, img_shape[0], img_shape[1])
gray_shape = (batch_size, 1, img_shape[0], img_shape[1])
fg = torch.from_numpy(np.random.random(color_shape).astype(np.float32))
bg = torch.from_numpy(np.random.random(color_shape).astype(np.float32))
merged = torch.from_numpy(np.random.random(color_shape).astype(np.float32))
alpha = torch.from_numpy(np.random.random(gray_shape).astype(np.float32))
trimap = torch.from_numpy(np.random.random(gray_shape).astype(np.float32))
if cuda:
fg = fg.cuda()
bg = bg.cuda()
merged = merged.cuda()
alpha = alpha.cuda()
trimap = trimap.cuda()
return fg, bg, merged, alpha, trimap
| 3,362 | 35.956044 | 79 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_backbones/test_encoder_decoders/test_encoders.py | # Copyright (c) OpenMMLab. All rights reserved.
from collections.abc import Iterable
import numpy as np
import pytest
import torch
from mmcv.utils.parrots_wrapper import _BatchNorm
from mmedit.models.backbones import (VGG16, DepthwiseIndexBlock,
FBAResnetDilated, HolisticIndexBlock,
IndexNetEncoder, ResGCAEncoder, ResNetEnc,
ResShortcutEnc)
from mmedit.models.backbones.encoder_decoders.encoders.resnet import (
BasicBlock, Bottleneck)
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)):
"""
Create a superset of inputs needed to run encoder.
Args:
input_shape (tuple): input batch dimensions.
Default: (1, 4, 64, 64).
"""
img = np.random.random(input_shape).astype(np.float32)
img = torch.from_numpy(img)
return img
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, 512, 2, 2))
assert_tensor_with_shape(outputs['max_idx_1'], target_shape[0])
assert_tensor_with_shape(outputs['max_idx_2'], target_shape[1])
assert_tensor_with_shape(outputs['max_idx_3'], target_shape[2])
assert_tensor_with_shape(outputs['max_idx_4'], target_shape[3])
assert_tensor_with_shape(outputs['max_idx_5'], target_shape[4])
model = VGG16(4, batch_norm=True)
model.init_weights()
model.train()
img = _demo_inputs()
outputs = model(img)
assert_tensor_with_shape(outputs['out'], (2, 512, 2, 2))
assert_tensor_with_shape(outputs['max_idx_1'], target_shape[0])
assert_tensor_with_shape(outputs['max_idx_2'], target_shape[1])
assert_tensor_with_shape(outputs['max_idx_3'], target_shape[2])
assert_tensor_with_shape(outputs['max_idx_4'], target_shape[3])
assert_tensor_with_shape(outputs['max_idx_5'], target_shape[4])
model = VGG16(4, aspp=True, dilations=[6, 12, 18])
model.init_weights()
model.train()
img = _demo_inputs()
outputs = model(img)
assert_tensor_with_shape(outputs['out'], (2, 256, 2, 2))
assert_tensor_with_shape(outputs['max_idx_1'], target_shape[0])
assert_tensor_with_shape(outputs['max_idx_2'], target_shape[1])
assert_tensor_with_shape(outputs['max_idx_3'], target_shape[2])
assert_tensor_with_shape(outputs['max_idx_4'], target_shape[3])
assert_tensor_with_shape(outputs['max_idx_5'], target_shape[4])
assert check_norm_state(model.modules(), True)
# test forward with gpu
if torch.cuda.is_available():
model = VGG16(4)
model.init_weights()
model.train()
model.cuda()
img = _demo_inputs().cuda()
outputs = model(img)
assert_tensor_with_shape(outputs['out'], (2, 512, 2, 2))
assert_tensor_with_shape(outputs['max_idx_1'], target_shape[0])
assert_tensor_with_shape(outputs['max_idx_2'], target_shape[1])
assert_tensor_with_shape(outputs['max_idx_3'], target_shape[2])
assert_tensor_with_shape(outputs['max_idx_4'], target_shape[3])
assert_tensor_with_shape(outputs['max_idx_5'], target_shape[4])
model = VGG16(4, batch_norm=True)
model.init_weights()
model.train()
model.cuda()
img = _demo_inputs().cuda()
outputs = model(img)
assert_tensor_with_shape(outputs['out'], (2, 512, 2, 2))
assert_tensor_with_shape(outputs['max_idx_1'], target_shape[0])
assert_tensor_with_shape(outputs['max_idx_2'], target_shape[1])
assert_tensor_with_shape(outputs['max_idx_3'], target_shape[2])
assert_tensor_with_shape(outputs['max_idx_4'], target_shape[3])
assert_tensor_with_shape(outputs['max_idx_5'], target_shape[4])
model = VGG16(4, aspp=True, dilations=[6, 12, 18])
model.init_weights()
model.train()
model.cuda()
img = _demo_inputs().cuda()
outputs = model(img)
assert_tensor_with_shape(outputs['out'], (2, 256, 2, 2))
assert_tensor_with_shape(outputs['max_idx_1'], target_shape[0])
assert_tensor_with_shape(outputs['max_idx_2'], target_shape[1])
assert_tensor_with_shape(outputs['max_idx_3'], target_shape[2])
assert_tensor_with_shape(outputs['max_idx_4'], target_shape[3])
assert_tensor_with_shape(outputs['max_idx_5'], target_shape[4])
assert check_norm_state(model.modules(), True)
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, 4, 2], 4, with_spectral_norm=True)
assert hasattr(model.conv1.conv, 'weight_orig')
model.init_weights()
model.train()
# trimap has 1 channels
img = _demo_inputs((2, 4, 64, 64))
feat = model(img)
assert_tensor_with_shape(feat, torch.Size([2, 512, 2, 2]))
# test resnet encoder with late downsample
model = ResNetEnc('BasicBlock', [3, 4, 4, 2], 6, late_downsample=True)
model.init_weights()
model.train()
# both image and trimap has 3 channels
img = _demo_inputs((2, 6, 64, 64))
feat = model(img)
assert_tensor_with_shape(feat, torch.Size([2, 512, 2, 2]))
if torch.cuda.is_available():
# repeat above code again
model = ResNetEnc(
'BasicBlock', [3, 4, 4, 2], 4, with_spectral_norm=True)
assert hasattr(model.conv1.conv, 'weight_orig')
model.init_weights()
model.train()
model.cuda()
# trimap has 1 channels
img = _demo_inputs((2, 4, 64, 64)).cuda()
feat = model(img)
assert_tensor_with_shape(feat, torch.Size([2, 512, 2, 2]))
# test resnet encoder with late downsample
model = ResNetEnc('BasicBlock', [3, 4, 4, 2], 6, late_downsample=True)
model.init_weights()
model.train()
model.cuda()
# both image and trimap has 3 channels
img = _demo_inputs((2, 6, 64, 64)).cuda()
feat = model(img)
assert_tensor_with_shape(feat, torch.Size([2, 512, 2, 2]))
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 shape for model with late downsample
target_late_ds_shape = [(2, 32, 64, 64), (2, 64, 32, 32), (2, 64, 16, 16),
(2, 128, 8, 8), (2, 256, 4, 4)]
model = ResShortcutEnc(
'BasicBlock', [3, 4, 4, 2], 4, with_spectral_norm=True)
assert hasattr(model.conv1.conv, 'weight_orig')
model.init_weights()
model.train()
# trimap has 1 channels
img = _demo_inputs((2, 4, 64, 64))
outputs = model(img)
assert_tensor_with_shape(outputs['out'], (2, 512, 2, 2))
assert_tensor_with_shape(outputs['feat1'], target_shape[0])
assert_tensor_with_shape(outputs['feat2'], target_shape[1])
assert_tensor_with_shape(outputs['feat3'], target_shape[2])
assert_tensor_with_shape(outputs['feat4'], target_shape[3])
assert_tensor_with_shape(outputs['feat5'], target_shape[4])
model = ResShortcutEnc('BasicBlock', [3, 4, 4, 2], 6)
model.init_weights()
model.train()
# both image and trimap has 3 channels
img = _demo_inputs((2, 6, 64, 64))
outputs = model(img)
assert_tensor_with_shape(outputs['out'], (2, 512, 2, 2))
assert_tensor_with_shape(outputs['feat1'], target_shape[0])
assert_tensor_with_shape(outputs['feat2'], target_shape[1])
assert_tensor_with_shape(outputs['feat3'], target_shape[2])
assert_tensor_with_shape(outputs['feat4'], target_shape[3])
assert_tensor_with_shape(outputs['feat5'], target_shape[4])
# test resnet shortcut encoder with late downsample
model = ResShortcutEnc('BasicBlock', [3, 4, 4, 2], 6, late_downsample=True)
model.init_weights()
model.train()
# both image and trimap has 3 channels
img = _demo_inputs((2, 6, 64, 64))
outputs = model(img)
assert_tensor_with_shape(outputs['out'], (2, 512, 2, 2))
assert_tensor_with_shape(outputs['feat1'], target_late_ds_shape[0])
assert_tensor_with_shape(outputs['feat2'], target_late_ds_shape[1])
assert_tensor_with_shape(outputs['feat3'], target_late_ds_shape[2])
assert_tensor_with_shape(outputs['feat4'], target_late_ds_shape[3])
assert_tensor_with_shape(outputs['feat5'], target_late_ds_shape[4])
if torch.cuda.is_available():
# repeat above code again
model = ResShortcutEnc(
'BasicBlock', [3, 4, 4, 2], 4, with_spectral_norm=True)
assert hasattr(model.conv1.conv, 'weight_orig')
model.init_weights()
model.train()
model.cuda()
# trimap has 1 channels
img = _demo_inputs((2, 4, 64, 64)).cuda()
outputs = model(img)
assert_tensor_with_shape(outputs['out'], (2, 512, 2, 2))
assert_tensor_with_shape(outputs['feat1'], target_shape[0])
assert_tensor_with_shape(outputs['feat2'], target_shape[1])
assert_tensor_with_shape(outputs['feat3'], target_shape[2])
assert_tensor_with_shape(outputs['feat4'], target_shape[3])
assert_tensor_with_shape(outputs['feat5'], target_shape[4])
model = ResShortcutEnc('BasicBlock', [3, 4, 4, 2], 6)
model.init_weights()
model.train()
model.cuda()
# both image and trimap has 3 channels
img = _demo_inputs((2, 6, 64, 64)).cuda()
outputs = model(img)
assert_tensor_with_shape(outputs['out'], (2, 512, 2, 2))
assert_tensor_with_shape(outputs['feat1'], target_shape[0])
assert_tensor_with_shape(outputs['feat2'], target_shape[1])
assert_tensor_with_shape(outputs['feat3'], target_shape[2])
assert_tensor_with_shape(outputs['feat4'], target_shape[3])
assert_tensor_with_shape(outputs['feat5'], target_shape[4])
# test resnet shortcut encoder with late downsample
model = ResShortcutEnc(
'BasicBlock', [3, 4, 4, 2], 6, late_downsample=True)
model.init_weights()
model.train()
model.cuda()
# both image and trimap has 3 channels
img = _demo_inputs((2, 6, 64, 64)).cuda()
outputs = model(img)
assert_tensor_with_shape(outputs['out'], (2, 512, 2, 2))
assert_tensor_with_shape(outputs['feat1'], target_late_ds_shape[0])
assert_tensor_with_shape(outputs['feat2'], target_late_ds_shape[1])
assert_tensor_with_shape(outputs['feat3'], target_late_ds_shape[2])
assert_tensor_with_shape(outputs['feat4'], target_late_ds_shape[3])
assert_tensor_with_shape(outputs['feat5'], target_late_ds_shape[4])
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 shape for model with late downsample
target_late_ds = [(2, 32, 64, 64), (2, 64, 32, 32), (2, 64, 16, 16),
(2, 128, 8, 8), (2, 256, 4, 4)]
model = ResGCAEncoder('BasicBlock', [3, 4, 4, 2], 4)
model.init_weights()
model.train()
# trimap has 1 channels
img = _demo_inputs((2, 4, 64, 64))
outputs = model(img)
assert_tensor_with_shape(outputs['out'], (2, 512, 2, 2))
assert_tensor_with_shape(outputs['img_feat'], (2, 128, 8, 8))
assert_tensor_with_shape(outputs['unknown'], (2, 1, 8, 8))
for i in range(5):
assert_tensor_with_shape(outputs[f'feat{i+1}'], target_shape[i])
model = ResGCAEncoder('BasicBlock', [3, 4, 4, 2], 6)
model.init_weights()
model.train()
# both image and trimap has 3 channels
img = _demo_inputs((2, 6, 64, 64))
outputs = model(img)
assert_tensor_with_shape(outputs['out'], (2, 512, 2, 2))
assert_tensor_with_shape(outputs['img_feat'], (2, 128, 8, 8))
assert_tensor_with_shape(outputs['unknown'], (2, 1, 8, 8))
for i in range(5):
assert_tensor_with_shape(outputs[f'feat{i+1}'], target_shape[i])
# test resnet shortcut encoder with late downsample
model = ResGCAEncoder('BasicBlock', [3, 4, 4, 2], 6, late_downsample=True)
model.init_weights()
model.train()
# both image and trimap has 3 channels
img = _demo_inputs((2, 6, 64, 64))
outputs = model(img)
assert_tensor_with_shape(outputs['out'], (2, 512, 2, 2))
assert_tensor_with_shape(outputs['img_feat'], (2, 128, 8, 8))
assert_tensor_with_shape(outputs['unknown'], (2, 1, 8, 8))
for i in range(5):
assert_tensor_with_shape(outputs[f'feat{i+1}'], target_late_ds[i])
if torch.cuda.is_available():
# repeat above code again
model = ResGCAEncoder('BasicBlock', [3, 4, 4, 2], 4)
model.init_weights()
model.train()
model.cuda()
# trimap has 1 channels
img = _demo_inputs((2, 4, 64, 64)).cuda()
outputs = model(img)
assert_tensor_with_shape(outputs['out'], (2, 512, 2, 2))
assert_tensor_with_shape(outputs['img_feat'], (2, 128, 8, 8))
assert_tensor_with_shape(outputs['unknown'], (2, 1, 8, 8))
for i in range(5):
assert_tensor_with_shape(outputs[f'feat{i+1}'], target_shape[i])
model = ResGCAEncoder('BasicBlock', [3, 4, 4, 2], 6)
model.init_weights()
model.train()
model.cuda()
# both image and trimap has 3 channels
img = _demo_inputs((2, 6, 64, 64)).cuda()
outputs = model(img)
assert_tensor_with_shape(outputs['out'], (2, 512, 2, 2))
assert_tensor_with_shape(outputs['img_feat'], (2, 128, 8, 8))
assert_tensor_with_shape(outputs['unknown'], (2, 1, 8, 8))
for i in range(5):
assert_tensor_with_shape(outputs[f'feat{i+1}'], target_shape[i])
# test resnet shortcut encoder with late downsample
model = ResGCAEncoder(
'BasicBlock', [3, 4, 4, 2], 6, late_downsample=True)
model.init_weights()
model.train()
model.cuda()
# both image and trimap has 3 channels
img = _demo_inputs((2, 6, 64, 64)).cuda()
outputs = model(img)
assert_tensor_with_shape(outputs['out'], (2, 512, 2, 2))
assert_tensor_with_shape(outputs['img_feat'], (2, 128, 8, 8))
assert_tensor_with_shape(outputs['unknown'], (2, 1, 8, 8))
for i in range(5):
assert_tensor_with_shape(outputs[f'feat{i+1}'], target_late_ds[i])
def test_index_blocks():
"""Test index blocks for indexnet encoder."""
# test holistic index block
# test holistic index block without context and nonlinearty
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, 1, 8, 8)
assert dec_idx_feat.shape == (2, 1, 8, 8)
# test holistic index block with context and nonlinearty
block = HolisticIndexBlock(128, use_context=True, use_nonlinear=True)
assert len(block.index_block) == 2 # nonlinear mode has two blocks
x = torch.rand(2, 128, 8, 8)
enc_idx_feat, dec_idx_feat = block(x)
assert enc_idx_feat.shape == (2, 1, 8, 8)
assert dec_idx_feat.shape == (2, 1, 8, 8)
# test depthwise index block
# test depthwise index block without context and nonlinearty in o2o mode
block = DepthwiseIndexBlock(
128, use_context=False, mode='oso', use_nonlinear=False)
assert not isinstance(block.index_blocks[0], Iterable)
x = torch.rand(2, 128, 8, 8)
enc_idx_feat, dec_idx_feat = block(x)
assert enc_idx_feat.shape == (2, 128, 8, 8)
assert dec_idx_feat.shape == (2, 128, 8, 8)
# test depthwise index block with context and nonlinearty in m2o mode
block = DepthwiseIndexBlock(
128, use_context=True, mode='m2o', use_nonlinear=True)
assert len(block.index_blocks[0]) == 2 # nonlinear mode has two blocks
x = torch.rand(2, 128, 8, 8)
enc_idx_feat, dec_idx_feat = block(x)
assert enc_idx_feat.shape == (2, 128, 8, 8)
assert dec_idx_feat.shape == (2, 128, 8, 8)
def test_indexnet_encoder():
"""Test Indexnet encoder."""
with pytest.raises(ValueError):
# out_stride must be 16 or 32
IndexNetEncoder(4, out_stride=8)
with pytest.raises(NameError):
# index_mode must be 'holistic', 'o2o' or 'm2o'
IndexNetEncoder(4, index_mode='unknown_mode')
# test indexnet encoder with default indexnet setting
indexnet_encoder = IndexNetEncoder(
4,
out_stride=32,
width_mult=1,
index_mode='m2o',
aspp=True,
use_nonlinear=True,
use_context=True)
indexnet_encoder.init_weights()
x = torch.rand(2, 4, 32, 32)
outputs = indexnet_encoder(x)
assert outputs['out'].shape == (2, 160, 1, 1)
assert len(outputs['shortcuts']) == 7
target_shapes = [(2, 32, 32, 32), (2, 16, 16, 16), (2, 24, 16, 16),
(2, 32, 8, 8), (2, 64, 4, 4), (2, 96, 2, 2),
(2, 160, 2, 2)]
for shortcut, target_shape in zip(outputs['shortcuts'], target_shapes):
assert shortcut.shape == target_shape
assert len(outputs['dec_idx_feat_list']) == 7
target_shapes = [(2, 32, 32, 32), None, (2, 24, 16, 16), (2, 32, 8, 8),
(2, 64, 4, 4), None, (2, 160, 2, 2)]
for dec_idx_feat, target_shape in zip(outputs['dec_idx_feat_list'],
target_shapes):
if dec_idx_feat is not None:
assert dec_idx_feat.shape == target_shape
# test indexnet encoder with other config
indexnet_encoder = IndexNetEncoder(
4,
out_stride=16,
width_mult=2,
index_mode='o2o',
aspp=False,
use_nonlinear=False,
use_context=False)
indexnet_encoder.init_weights()
x = torch.rand(2, 4, 32, 32)
outputs = indexnet_encoder(x)
assert outputs['out'].shape == (2, 160, 2, 2)
assert len(outputs['shortcuts']) == 7
target_shapes = [(2, 64, 32, 32), (2, 32, 16, 16), (2, 48, 16, 16),
(2, 64, 8, 8), (2, 128, 4, 4), (2, 192, 2, 2),
(2, 320, 2, 2)]
for shortcut, target_shape in zip(outputs['shortcuts'], target_shapes):
assert shortcut.shape == target_shape
assert len(outputs['dec_idx_feat_list']) == 7
target_shapes = [(2, 64, 32, 32), None, (2, 48, 16, 16), (2, 64, 8, 8),
(2, 128, 4, 4), None, None]
for dec_idx_feat, target_shape in zip(outputs['dec_idx_feat_list'],
target_shapes):
if dec_idx_feat is not None:
assert dec_idx_feat.shape == target_shape
# test indexnet encoder with holistic index block
indexnet_encoder = IndexNetEncoder(
4,
out_stride=16,
width_mult=2,
index_mode='holistic',
aspp=False,
freeze_bn=True,
use_nonlinear=False,
use_context=False)
indexnet_encoder.init_weights()
x = torch.rand(2, 4, 32, 32)
outputs = indexnet_encoder(x)
assert outputs['out'].shape == (2, 160, 2, 2)
assert len(outputs['shortcuts']) == 7
target_shapes = [(2, 64, 32, 32), (2, 32, 16, 16), (2, 48, 16, 16),
(2, 64, 8, 8), (2, 128, 4, 4), (2, 192, 2, 2),
(2, 320, 2, 2)]
for shortcut, target_shape in zip(outputs['shortcuts'], target_shapes):
assert shortcut.shape == target_shape
assert len(outputs['dec_idx_feat_list']) == 7
target_shapes = [(2, 1, 32, 32), None, (2, 1, 16, 16), (2, 1, 8, 8),
(2, 1, 4, 4), None, None]
for dec_idx_feat, target_shape in zip(outputs['dec_idx_feat_list'],
target_shapes):
if dec_idx_feat is not None:
assert dec_idx_feat.shape == target_shape
def test_fba_encoder():
"""Test FBA encoder."""
with pytest.raises(KeyError):
# ResNet depth should be in [18, 34, 50, 101, 152]
FBAResnetDilated(
20,
in_channels=11,
stem_channels=64,
base_channels=64,
)
with pytest.raises(AssertionError):
# In ResNet: 1 <= num_stages <= 4
FBAResnetDilated(
50,
in_channels=11,
stem_channels=64,
base_channels=64,
num_stages=0)
with pytest.raises(AssertionError):
# In ResNet: 1 <= num_stages <= 4
FBAResnetDilated(
50,
in_channels=11,
stem_channels=64,
base_channels=64,
num_stages=5)
with pytest.raises(AssertionError):
# len(strides) == len(dilations) == num_stages
FBAResnetDilated(
50,
in_channels=11,
stem_channels=64,
base_channels=64,
strides=(1, ),
dilations=(1, 1),
num_stages=3)
with pytest.raises(TypeError):
# pretrained must be a string path
model = FBAResnetDilated(
50,
in_channels=11,
stem_channels=64,
base_channels=64,
)
model.init_weights(pretrained=233)
model = FBAResnetDilated(
depth=50,
in_channels=11,
stem_channels=64,
base_channels=64,
conv_cfg=dict(type='ConvWS'),
norm_cfg=dict(type='GN', num_groups=32))
model.init_weights()
model.train()
input = _demo_inputs((1, 14, 320, 320))
output = model(input)
assert 'conv_out' in output.keys()
assert 'merged' in output.keys()
assert 'two_channel_trimap' in output.keys()
assert isinstance(output['conv_out'], list)
assert len(output['conv_out']) == 6
assert isinstance(output['merged'], torch.Tensor)
assert_tensor_with_shape(output['merged'], torch.Size([1, 3, 320, 320]))
assert isinstance(output['two_channel_trimap'], torch.Tensor)
assert_tensor_with_shape(output['two_channel_trimap'],
torch.Size([1, 2, 320, 320]))
if torch.cuda.is_available():
model = FBAResnetDilated(
depth=50,
in_channels=11,
stem_channels=64,
base_channels=64,
conv_cfg=dict(type='ConvWS'),
norm_cfg=dict(type='GN', num_groups=32))
model.init_weights()
model.train()
model.cuda()
input = _demo_inputs((1, 14, 320, 320)).cuda()
output = model(input)
assert 'conv_out' in output.keys()
assert 'merged' in output.keys()
assert 'two_channel_trimap' in output.keys()
assert isinstance(output['conv_out'], list)
assert len(output['conv_out']) == 6
assert isinstance(output['merged'], torch.Tensor)
assert_tensor_with_shape(output['merged'], torch.Size([1, 3, 320,
320]))
assert isinstance(output['two_channel_trimap'], torch.Tensor)
assert_tensor_with_shape(output['two_channel_trimap'],
torch.Size([1, 2, 320, 320]))
| 24,631 | 38.22293 | 79 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_backbones/test_encoder_decoders/test_pconv_encdec.py | # Copyright (c) OpenMMLab. All rights reserved.
import pytest
import torch
from mmcv.utils.parrots_wrapper import _BatchNorm
from mmedit.models.backbones import PConvEncoder, PConvEncoderDecoder
def test_pconv_encdec():
pconv_enc_cfg = dict(type='PConvEncoder')
pconv_dec_cfg = dict(type='PConvDecoder')
if torch.cuda.is_available():
pconv_encdec = PConvEncoderDecoder(pconv_enc_cfg, pconv_dec_cfg)
pconv_encdec.init_weights()
pconv_encdec.cuda()
x = torch.randn((1, 3, 256, 256)).cuda()
mask = torch.ones_like(x)
mask[..., 50:150, 100:250] = 1.
res, updated_mask = pconv_encdec(x, mask)
assert res.shape == (1, 3, 256, 256)
assert mask.shape == (1, 3, 256, 256)
with pytest.raises(TypeError):
pconv_encdec.init_weights(pretrained=dict(igccc=8989))
def test_pconv_enc():
pconv_enc = PConvEncoder(norm_eval=False)
pconv_enc.train()
for name, module in pconv_enc.named_modules():
if isinstance(module, _BatchNorm):
assert module.training
pconv_enc = PConvEncoder(norm_eval=True)
pconv_enc.train()
for name, module in pconv_enc.named_modules():
if isinstance(module, _BatchNorm):
assert not module.training
| 1,280 | 31.025 | 72 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_backbones/test_encoder_decoders/test_deepfill_encdec.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch
from mmedit.models.backbones import DeepFillEncoderDecoder, GLEncoderDecoder
from mmedit.models.components import DeepFillRefiner
def test_deepfill_encdec():
encdec = DeepFillEncoderDecoder()
assert isinstance(encdec.stage1, GLEncoderDecoder)
assert isinstance(encdec.stage2, DeepFillRefiner)
if torch.cuda.is_available():
img = torch.rand((2, 3, 256, 256)).cuda()
mask = img.new_zeros((2, 1, 256, 256))
mask[..., 20:100, 30:120] = 1.
input_x = torch.cat([img, torch.ones_like(mask), mask], dim=1)
encdec.cuda()
stage1_res, stage2_res = encdec(input_x)
assert stage1_res.shape == (2, 3, 256, 256)
assert stage2_res.shape == (2, 3, 256, 256)
encdec = DeepFillEncoderDecoder(return_offset=True).cuda()
stage1_res, stage2_res, offset = encdec(input_x)
assert offset.shape == (2, 32, 32, 32, 32)
| 961 | 37.48 | 76 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_extractors/test_feedback_hour_glass.py | # Copyright (c) OpenMMLab. All rights reserved.
import pytest
import torch
from mmedit.models import build_component
from mmedit.models.extractors import Hourglass
from mmedit.models.extractors.feedback_hour_glass import (
ResBlock, reduce_to_five_heatmaps)
def test_res_block():
res_block = ResBlock(16, 32)
x = torch.rand(2, 16, 64, 64)
y = res_block(x)
assert y.shape == (2, 32, 64, 64)
res_block = ResBlock(16, 16)
x = torch.rand(2, 16, 64, 64)
y = res_block(x)
assert y.shape == (2, 16, 64, 64)
def test_hour_glass():
hour_glass = Hourglass(2, 16)
x = torch.rand(2, 16, 64, 64)
y = hour_glass(x)
assert y.shape == x.shape
def test_feedback_hour_glass():
model_cfg = dict(
type='FeedbackHourglass', mid_channels=16, num_keypoints=20)
fhg = build_component(model_cfg)
assert fhg.__class__.__name__ == 'FeedbackHourglass'
x = torch.rand(2, 3, 64, 64)
heatmap, last_hidden = fhg.forward(x)
assert heatmap.shape == (2, 20, 16, 16)
assert last_hidden.shape == (2, 16, 16, 16)
heatmap, last_hidden = fhg.forward(x, last_hidden)
assert heatmap.shape == (2, 20, 16, 16)
assert last_hidden.shape == (2, 16, 16, 16)
def test_reduce_to_five_heatmaps():
heatmap = torch.rand((2, 5, 64, 64))
new_heatmap = reduce_to_five_heatmaps(heatmap, False)
assert new_heatmap.shape == (2, 5, 64, 64)
new_heatmap = reduce_to_five_heatmaps(heatmap, True)
assert new_heatmap.shape == (2, 5, 64, 64)
heatmap = torch.rand((2, 68, 64, 64))
new_heatmap = reduce_to_five_heatmaps(heatmap, False)
assert new_heatmap.shape == (2, 5, 64, 64)
new_heatmap = reduce_to_five_heatmaps(heatmap, True)
assert new_heatmap.shape == (2, 5, 64, 64)
heatmap = torch.rand((2, 194, 64, 64))
new_heatmap = reduce_to_five_heatmaps(heatmap, False)
assert new_heatmap.shape == (2, 5, 64, 64)
new_heatmap = reduce_to_five_heatmaps(heatmap, True)
assert new_heatmap.shape == (2, 5, 64, 64)
with pytest.raises(NotImplementedError):
heatmap = torch.rand((2, 12, 64, 64))
reduce_to_five_heatmaps(heatmap, False)
| 2,154 | 30.231884 | 68 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_extractors/test_lte.py | # Copyright (c) OpenMMLab. All rights reserved.
import pytest
import torch
from mmedit.models import build_component
def test_lte():
model_cfg = dict(
type='LTE',
requires_grad=False,
pixel_range=1.,
pretrained=None,
load_pretrained_vgg=False)
lte = build_component(model_cfg)
assert lte.__class__.__name__ == 'LTE'
x = torch.rand(2, 3, 64, 64)
x_level3, x_level2, x_level1 = lte(x)
assert x_level1.shape == (2, 64, 64, 64)
assert x_level2.shape == (2, 128, 32, 32)
assert x_level3.shape == (2, 256, 16, 16)
lte.init_weights(None)
with pytest.raises(IOError):
model_cfg['pretrained'] = ''
lte = build_component(model_cfg)
x_level3, x_level2, x_level1 = lte(x)
lte.init_weights('')
with pytest.raises(TypeError):
lte.init_weights(1)
| 863 | 24.411765 | 47 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_synthesizers/test_cyclegan.py | # Copyright (c) OpenMMLab. All rights reserved.
import copy
from unittest.mock import patch
import mmcv
import pytest
import torch
from mmcv.parallel import DataContainer as DC
from mmcv.runner import obj_from_dict
from mmedit.models import build_model
from mmedit.models.backbones import ResnetGenerator
from mmedit.models.components import PatchDiscriminator
from mmedit.models.losses import GANLoss, L1Loss
def test_cyclegan():
model_cfg = dict(
type='CycleGAN',
generator=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)),
discriminator=dict(
type='PatchDiscriminator',
in_channels=3,
base_channels=64,
num_conv=3,
norm_cfg=dict(type='IN'),
init_cfg=dict(type='normal', gain=0.02)),
gan_loss=dict(
type='GANLoss',
gan_type='lsgan',
real_label_val=1.0,
fake_label_val=0,
loss_weight=1.0),
cycle_loss=dict(type='L1Loss', loss_weight=10.0, reduction='mean'),
id_loss=dict(type='L1Loss', loss_weight=0.5, reduction='mean'))
train_cfg = None
test_cfg = None
# build synthesizer
synthesizer = build_model(
model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
# test checking if id loss > 0, in_channels == out_channels
with pytest.raises(AssertionError):
bad_model_cfg = copy.deepcopy(model_cfg)
bad_model_cfg['generator']['out_channels'] = 1
_ = build_model(bad_model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
# test checking gan loss cannot be None
with pytest.raises(AssertionError):
bad_model_cfg = copy.deepcopy(model_cfg)
bad_model_cfg['gan_loss'] = None
_ = build_model(bad_model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
# test checking cycle loss cannot be None
with pytest.raises(AssertionError):
bad_model_cfg = copy.deepcopy(model_cfg)
bad_model_cfg['cycle_loss'] = None
_ = build_model(bad_model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
# test attributes
assert synthesizer.__class__.__name__ == 'CycleGAN'
assert isinstance(synthesizer.generators['a'], ResnetGenerator)
assert isinstance(synthesizer.generators['b'], ResnetGenerator)
assert isinstance(synthesizer.discriminators['a'], PatchDiscriminator)
assert isinstance(synthesizer.discriminators['b'], PatchDiscriminator)
assert isinstance(synthesizer.gan_loss, GANLoss)
assert isinstance(synthesizer.cycle_loss, L1Loss)
assert isinstance(synthesizer.id_loss, L1Loss)
assert synthesizer.train_cfg is None
assert synthesizer.test_cfg is None
# prepare data
inputs = torch.rand(1, 3, 64, 64)
targets = torch.rand(1, 3, 64, 64)
data_batch = {'img_a': inputs, 'img_b': targets}
img_meta = {}
img_meta['img_a_path'] = 'img_a_path'
img_meta['img_b_path'] = 'img_b_path'
data_batch['meta'] = [img_meta]
# prepare optimizer
optim_cfg = dict(type='Adam', lr=2e-4, betas=(0.5, 0.999))
optimizer = {
'generators':
obj_from_dict(
optim_cfg, torch.optim,
dict(params=getattr(synthesizer, 'generators').parameters())),
'discriminators':
obj_from_dict(
optim_cfg, torch.optim,
dict(params=getattr(synthesizer, 'discriminators').parameters()))
}
# test forward_dummy
with torch.no_grad():
output = synthesizer.forward_dummy(data_batch['img_a'])
assert torch.is_tensor(output)
assert output.size() == (1, 3, 64, 64)
# test forward_test
with torch.no_grad():
outputs = synthesizer(inputs, targets, [img_meta], test_mode=True)
assert torch.equal(outputs['real_a'], data_batch['img_a'])
assert torch.equal(outputs['real_b'], data_batch['img_b'])
assert torch.is_tensor(outputs['fake_b'])
assert torch.is_tensor(outputs['fake_a'])
assert outputs['fake_b'].size() == (1, 3, 64, 64)
assert outputs['fake_a'].size() == (1, 3, 64, 64)
# val_step
with torch.no_grad():
outputs = synthesizer.val_step(data_batch)
assert torch.equal(outputs['real_a'], data_batch['img_a'])
assert torch.equal(outputs['real_b'], data_batch['img_b'])
assert torch.is_tensor(outputs['fake_b'])
assert torch.is_tensor(outputs['fake_a'])
assert outputs['fake_b'].size() == (1, 3, 64, 64)
assert outputs['fake_a'].size() == (1, 3, 64, 64)
# test forward_train
outputs = synthesizer(inputs, targets, [img_meta], test_mode=False)
assert torch.equal(outputs['real_a'], data_batch['img_a'])
assert torch.equal(outputs['real_b'], data_batch['img_b'])
assert torch.is_tensor(outputs['fake_b'])
assert torch.is_tensor(outputs['fake_a'])
assert torch.is_tensor(outputs['rec_a'])
assert torch.is_tensor(outputs['rec_b'])
assert outputs['fake_b'].size() == (1, 3, 64, 64)
assert outputs['fake_a'].size() == (1, 3, 64, 64)
assert outputs['rec_a'].size() == (1, 3, 64, 64)
assert outputs['rec_b'].size() == (1, 3, 64, 64)
# test train_step
outputs = synthesizer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
assert isinstance(outputs['results'], dict)
for v in [
'loss_gan_d_a', 'loss_gan_d_b', 'loss_id_a', 'loss_id_b',
'loss_gan_g_a', 'loss_gan_g_b', 'loss_cycle_a', 'loss_cycle_b'
]:
assert isinstance(outputs['log_vars'][v], float)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['real_a'], data_batch['img_a'])
assert torch.equal(outputs['results']['real_b'], data_batch['img_b'])
assert torch.is_tensor(outputs['results']['fake_b'])
assert torch.is_tensor(outputs['results']['fake_a'])
assert outputs['results']['fake_b'].size() == (1, 3, 64, 64)
assert outputs['results']['fake_a'].size() == (1, 3, 64, 64)
# test train_step and forward_test (gpu)
if torch.cuda.is_available():
synthesizer = synthesizer.cuda()
optimizer = {
'generators':
obj_from_dict(
optim_cfg, torch.optim,
dict(params=getattr(synthesizer, 'generators').parameters())),
'discriminators':
obj_from_dict(
optim_cfg, torch.optim,
dict(
params=getattr(synthesizer,
'discriminators').parameters()))
}
data_batch_cuda = copy.deepcopy(data_batch)
data_batch_cuda['img_a'] = inputs.cuda()
data_batch_cuda['img_b'] = targets.cuda()
data_batch_cuda['meta'] = [DC(img_meta, cpu_only=True).data]
# forward_test
with torch.no_grad():
outputs = synthesizer(
data_batch_cuda['img_a'],
data_batch_cuda['img_b'],
data_batch_cuda['meta'],
test_mode=True)
assert torch.equal(outputs['real_a'], data_batch_cuda['img_a'].cpu())
assert torch.equal(outputs['real_b'], data_batch_cuda['img_b'].cpu())
assert torch.is_tensor(outputs['fake_b'])
assert torch.is_tensor(outputs['fake_a'])
assert outputs['fake_b'].size() == (1, 3, 64, 64)
assert outputs['fake_a'].size() == (1, 3, 64, 64)
# val_step
with torch.no_grad():
outputs = synthesizer.val_step(data_batch_cuda)
assert torch.equal(outputs['real_a'], data_batch_cuda['img_a'].cpu())
assert torch.equal(outputs['real_b'], data_batch_cuda['img_b'].cpu())
assert torch.is_tensor(outputs['fake_b'])
assert torch.is_tensor(outputs['fake_a'])
assert outputs['fake_b'].size() == (1, 3, 64, 64)
assert outputs['fake_a'].size() == (1, 3, 64, 64)
# test forward_train
outputs = synthesizer(
data_batch_cuda['img_a'],
data_batch_cuda['img_b'],
data_batch_cuda['meta'],
test_mode=False)
assert torch.equal(outputs['real_a'], data_batch_cuda['img_a'])
assert torch.equal(outputs['real_b'], data_batch_cuda['img_b'])
assert torch.is_tensor(outputs['fake_b'])
assert torch.is_tensor(outputs['fake_a'])
assert torch.is_tensor(outputs['rec_a'])
assert torch.is_tensor(outputs['rec_b'])
assert outputs['fake_b'].size() == (1, 3, 64, 64)
assert outputs['fake_a'].size() == (1, 3, 64, 64)
assert outputs['rec_a'].size() == (1, 3, 64, 64)
assert outputs['rec_b'].size() == (1, 3, 64, 64)
# train_step
outputs = synthesizer.train_step(data_batch_cuda, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
assert isinstance(outputs['results'], dict)
for v in [
'loss_gan_d_a', 'loss_gan_d_b', 'loss_id_a', 'loss_id_b',
'loss_gan_g_a', 'loss_gan_g_b', 'loss_cycle_a', 'loss_cycle_b'
]:
assert isinstance(outputs['log_vars'][v], float)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['real_a'],
data_batch_cuda['img_a'].cpu())
assert torch.equal(outputs['results']['real_b'],
data_batch_cuda['img_b'].cpu())
assert torch.is_tensor(outputs['results']['fake_b'])
assert torch.is_tensor(outputs['results']['fake_a'])
assert outputs['results']['fake_b'].size() == (1, 3, 64, 64)
assert outputs['results']['fake_a'].size() == (1, 3, 64, 64)
# test disc_steps and disc_init_steps
data_batch['img_a'] = inputs.cpu()
data_batch['img_b'] = targets.cpu()
train_cfg = dict(disc_steps=2, disc_init_steps=2)
synthesizer = build_model(
model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
optimizer = {
'generators':
obj_from_dict(
optim_cfg, torch.optim,
dict(params=getattr(synthesizer, 'generators').parameters())),
'discriminators':
obj_from_dict(
optim_cfg, torch.optim,
dict(params=getattr(synthesizer, 'discriminators').parameters()))
}
# iter 0, 1
for i in range(2):
assert synthesizer.step_counter == i
outputs = synthesizer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
assert isinstance(outputs['results'], dict)
for v in [
'loss_id_a', 'loss_id_b', 'loss_gan_g_a', 'loss_gan_g_b',
'loss_cycle_a', 'loss_cycle_b'
]:
assert outputs['log_vars'].get(v) is None
assert isinstance(outputs['log_vars']['loss_gan_d_a'], float)
assert isinstance(outputs['log_vars']['loss_gan_d_b'], float)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['real_a'], data_batch['img_a'])
assert torch.equal(outputs['results']['real_b'], data_batch['img_b'])
assert torch.is_tensor(outputs['results']['fake_b'])
assert torch.is_tensor(outputs['results']['fake_a'])
assert outputs['results']['fake_b'].size() == (1, 3, 64, 64)
assert outputs['results']['fake_a'].size() == (1, 3, 64, 64)
assert synthesizer.step_counter == i + 1
# iter 2, 3, 4, 5
for i in range(2, 6):
assert synthesizer.step_counter == i
outputs = synthesizer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
assert isinstance(outputs['results'], dict)
log_check_list = [
'loss_gan_d_a', 'loss_gan_d_b', 'loss_id_a', 'loss_id_b',
'loss_gan_g_a', 'loss_gan_g_b', 'loss_cycle_a', 'loss_cycle_b'
]
if i % 2 == 1:
log_None_list = [
'loss_id_a', 'loss_id_b', 'loss_gan_g_a', 'loss_gan_g_b',
'loss_cycle_a', 'loss_cycle_b'
]
for v in log_None_list:
assert outputs['log_vars'].get(v) is None
log_check_list.remove(v)
for v in log_check_list:
assert isinstance(outputs['log_vars'][v], float)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['real_a'], data_batch['img_a'])
assert torch.equal(outputs['results']['real_b'], data_batch['img_b'])
assert torch.is_tensor(outputs['results']['fake_b'])
assert torch.is_tensor(outputs['results']['fake_a'])
assert outputs['results']['fake_b'].size() == (1, 3, 64, 64)
assert outputs['results']['fake_a'].size() == (1, 3, 64, 64)
assert synthesizer.step_counter == i + 1
# test without id loss
model_cfg_ = copy.deepcopy(model_cfg)
model_cfg_.pop('id_loss')
synthesizer = build_model(model_cfg_, train_cfg=None, test_cfg=None)
optimizer = {
'generators':
obj_from_dict(
optim_cfg, torch.optim,
dict(params=getattr(synthesizer, 'generators').parameters())),
'discriminators':
obj_from_dict(
optim_cfg, torch.optim,
dict(params=getattr(synthesizer, 'discriminators').parameters()))
}
data_batch['img_a'] = inputs.cpu()
data_batch['img_b'] = targets.cpu()
outputs = synthesizer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
assert isinstance(outputs['results'], dict)
assert outputs['log_vars'].get('loss_id_a') is None
assert outputs['log_vars'].get('loss_id_b') is None
log_check_list = [
'loss_gan_d_a', 'loss_gan_d_b', 'loss_gan_g_a', 'loss_gan_g_b',
'loss_cycle_a', 'loss_cycle_b'
]
for v in log_check_list:
assert isinstance(outputs['log_vars'][v], float)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['real_a'], data_batch['img_a'])
assert torch.equal(outputs['results']['real_b'], data_batch['img_b'])
assert torch.is_tensor(outputs['results']['fake_b'])
assert torch.is_tensor(outputs['results']['fake_a'])
assert outputs['results']['fake_b'].size() == (1, 3, 64, 64)
assert outputs['results']['fake_a'].size() == (1, 3, 64, 64)
# test b2a translation
data_batch['img_a'] = inputs.cpu()
data_batch['img_b'] = targets.cpu()
train_cfg = dict(direction='b2a')
synthesizer = build_model(
model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
optimizer = {
'generators':
obj_from_dict(
optim_cfg, torch.optim,
dict(params=getattr(synthesizer, 'generators').parameters())),
'discriminators':
obj_from_dict(
optim_cfg, torch.optim,
dict(params=getattr(synthesizer, 'discriminators').parameters()))
}
assert synthesizer.step_counter == 0
outputs = synthesizer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
assert isinstance(outputs['results'], dict)
for v in [
'loss_gan_d_a', 'loss_gan_d_b', 'loss_id_a', 'loss_id_b',
'loss_gan_g_a', 'loss_gan_g_b', 'loss_cycle_a', 'loss_cycle_b'
]:
assert isinstance(outputs['log_vars'][v], float)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['real_a'], data_batch['img_b'])
assert torch.equal(outputs['results']['real_b'], data_batch['img_a'])
assert torch.is_tensor(outputs['results']['fake_b'])
assert torch.is_tensor(outputs['results']['fake_a'])
assert outputs['results']['fake_b'].size() == (1, 3, 64, 64)
assert outputs['results']['fake_a'].size() == (1, 3, 64, 64)
assert synthesizer.step_counter == 1
# test GAN image buffer size = 0
data_batch['img_a'] = inputs.cpu()
data_batch['img_b'] = targets.cpu()
train_cfg = dict(buffer_size=0)
synthesizer = build_model(
model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
optimizer = {
'generators':
obj_from_dict(
optim_cfg, torch.optim,
dict(params=getattr(synthesizer, 'generators').parameters())),
'discriminators':
obj_from_dict(
optim_cfg, torch.optim,
dict(params=getattr(synthesizer, 'discriminators').parameters()))
}
assert synthesizer.step_counter == 0
outputs = synthesizer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
assert isinstance(outputs['results'], dict)
for v in [
'loss_gan_d_a', 'loss_gan_d_b', 'loss_id_a', 'loss_id_b',
'loss_gan_g_a', 'loss_gan_g_b', 'loss_cycle_a', 'loss_cycle_b'
]:
assert isinstance(outputs['log_vars'][v], float)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['real_a'], data_batch['img_a'])
assert torch.equal(outputs['results']['real_b'], data_batch['img_b'])
assert torch.is_tensor(outputs['results']['fake_b'])
assert torch.is_tensor(outputs['results']['fake_a'])
assert outputs['results']['fake_b'].size() == (1, 3, 64, 64)
assert outputs['results']['fake_a'].size() == (1, 3, 64, 64)
assert synthesizer.step_counter == 1
# test save image
# show input
train_cfg = None
test_cfg = dict(show_input=True)
synthesizer = build_model(
model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
with patch.object(mmcv, 'imwrite', return_value=True):
# test save path not None Assertion
with pytest.raises(AssertionError):
with torch.no_grad():
_ = synthesizer(
inputs,
targets, [img_meta],
test_mode=True,
save_image=True)
# iteration is None
with torch.no_grad():
outputs = synthesizer(
inputs,
targets, [img_meta],
test_mode=True,
save_image=True,
save_path='save_path')
assert torch.equal(outputs['real_a'], data_batch['img_a'])
assert torch.equal(outputs['real_b'], data_batch['img_b'])
assert torch.is_tensor(outputs['fake_b'])
assert torch.is_tensor(outputs['fake_a'])
assert outputs['fake_b'].size() == (1, 3, 64, 64)
assert outputs['fake_a'].size() == (1, 3, 64, 64)
assert outputs['saved_flag']
# iteration is not None
with torch.no_grad():
outputs = synthesizer(
inputs,
targets, [img_meta],
test_mode=True,
save_image=True,
save_path='save_path',
iteration=1000)
assert torch.equal(outputs['real_a'], data_batch['img_a'])
assert torch.equal(outputs['real_b'], data_batch['img_b'])
assert torch.is_tensor(outputs['fake_b'])
assert torch.is_tensor(outputs['fake_a'])
assert outputs['fake_b'].size() == (1, 3, 64, 64)
assert outputs['fake_a'].size() == (1, 3, 64, 64)
assert outputs['saved_flag']
# not show input, test_direction a2b
train_cfg = None
test_cfg = dict(show_input=False, test_direction='a2b')
synthesizer = build_model(
model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
with patch.object(mmcv, 'imwrite', return_value=True):
# test save path not None Assertion
with pytest.raises(AssertionError):
with torch.no_grad():
_ = synthesizer(
inputs,
targets, [img_meta],
test_mode=True,
save_image=True)
# iteration is None
with torch.no_grad():
outputs = synthesizer(
inputs,
targets, [img_meta],
test_mode=True,
save_image=True,
save_path='save_path')
assert torch.equal(outputs['real_a'], data_batch['img_a'])
assert torch.equal(outputs['real_b'], data_batch['img_b'])
assert torch.is_tensor(outputs['fake_b'])
assert torch.is_tensor(outputs['fake_a'])
assert outputs['fake_b'].size() == (1, 3, 64, 64)
assert outputs['fake_a'].size() == (1, 3, 64, 64)
assert outputs['saved_flag']
# iteration is not None
with torch.no_grad():
outputs = synthesizer(
inputs,
targets, [img_meta],
test_mode=True,
save_image=True,
save_path='save_path',
iteration=1000)
assert torch.equal(outputs['real_a'], data_batch['img_a'])
assert torch.equal(outputs['real_b'], data_batch['img_b'])
assert torch.is_tensor(outputs['fake_b'])
assert torch.is_tensor(outputs['fake_a'])
assert outputs['fake_b'].size() == (1, 3, 64, 64)
assert outputs['fake_a'].size() == (1, 3, 64, 64)
assert outputs['saved_flag']
# not show input, test_direction b2a
train_cfg = None
test_cfg = dict(show_input=False, test_direction='b2a')
synthesizer = build_model(
model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
with patch.object(mmcv, 'imwrite', return_value=True):
# test save path not None Assertion
with pytest.raises(AssertionError):
with torch.no_grad():
_ = synthesizer(
inputs,
targets, [img_meta],
test_mode=True,
save_image=True)
# iteration is None
with torch.no_grad():
outputs = synthesizer(
inputs,
targets, [img_meta],
test_mode=True,
save_image=True,
save_path='save_path')
assert torch.equal(outputs['real_a'], data_batch['img_a'])
assert torch.equal(outputs['real_b'], data_batch['img_b'])
assert torch.is_tensor(outputs['fake_b'])
assert torch.is_tensor(outputs['fake_a'])
assert outputs['fake_b'].size() == (1, 3, 64, 64)
assert outputs['fake_a'].size() == (1, 3, 64, 64)
assert outputs['saved_flag']
# iteration is not None
with torch.no_grad():
outputs = synthesizer(
inputs,
targets, [img_meta],
test_mode=True,
save_image=True,
save_path='save_path',
iteration=1000)
assert torch.equal(outputs['real_a'], data_batch['img_a'])
assert torch.equal(outputs['real_b'], data_batch['img_b'])
assert torch.is_tensor(outputs['fake_b'])
assert torch.is_tensor(outputs['fake_a'])
assert outputs['fake_b'].size() == (1, 3, 64, 64)
assert outputs['fake_a'].size() == (1, 3, 64, 64)
assert outputs['saved_flag']
| 23,294 | 40.747312 | 78 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_restorers/test_basicvsr_model.py | # Copyright (c) OpenMMLab. All rights reserved.
import tempfile
import mmcv
import pytest
import torch
from mmcv.runner import obj_from_dict
from mmedit.models import build_model
from mmedit.models.backbones.sr_backbones import BasicVSRNet
from mmedit.models.losses import MSELoss
def test_basicvsr_model():
model_cfg = dict(
type='BasicVSR',
generator=dict(
type='BasicVSRNet',
mid_channels=64,
num_blocks=30,
spynet_pretrained=None),
pixel_loss=dict(type='MSELoss', loss_weight=1.0, reduction='sum'),
)
train_cfg = dict(fix_iter=1)
train_cfg = mmcv.Config(train_cfg)
test_cfg = None
# build restorer
restorer = build_model(model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
# test attributes
assert restorer.__class__.__name__ == 'BasicVSR'
assert isinstance(restorer.generator, BasicVSRNet)
assert isinstance(restorer.pixel_loss, MSELoss)
# prepare data
inputs = torch.rand(1, 5, 3, 64, 64)
targets = torch.rand(1, 5, 3, 256, 256)
if torch.cuda.is_available():
inputs = inputs.cuda()
targets = targets.cuda()
restorer = restorer.cuda()
# prepare data and optimizer
data_batch = {'lq': inputs, 'gt': targets}
optim_cfg = dict(type='Adam', lr=2e-4, betas=(0.9, 0.999))
optimizer = {
'generator':
obj_from_dict(optim_cfg, torch.optim,
dict(params=getattr(restorer, 'generator').parameters()))
}
# train_step (without updating spynet)
outputs = restorer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
assert isinstance(outputs['log_vars']['loss_pix'], float)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['lq'], data_batch['lq'].cpu())
assert torch.equal(outputs['results']['gt'], data_batch['gt'].cpu())
assert torch.is_tensor(outputs['results']['output'])
assert outputs['results']['output'].size() == (1, 5, 3, 256, 256)
# train with spynet updated
outputs = restorer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
assert isinstance(outputs['log_vars']['loss_pix'], float)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['lq'], data_batch['lq'].cpu())
assert torch.equal(outputs['results']['gt'], data_batch['gt'].cpu())
assert torch.is_tensor(outputs['results']['output'])
assert outputs['results']['output'].size() == (1, 5, 3, 256, 256)
# test forward_dummy
with torch.no_grad():
output = restorer.forward_dummy(data_batch['lq'])
assert torch.is_tensor(output)
assert output.size() == (1, 5, 3, 256, 256)
# forward_test
with torch.no_grad():
outputs = restorer(**data_batch, test_mode=True)
assert torch.equal(outputs['lq'], data_batch['lq'].cpu())
assert torch.equal(outputs['gt'], data_batch['gt'].cpu())
assert torch.is_tensor(outputs['output'])
assert outputs['output'].size() == (1, 5, 3, 256, 256)
with torch.no_grad():
outputs = restorer(inputs, test_mode=True)
assert torch.equal(outputs['lq'], data_batch['lq'].cpu())
assert torch.is_tensor(outputs['output'])
assert outputs['output'].size() == (1, 5, 3, 256, 256)
# test with metric and save image
train_cfg = mmcv.ConfigDict(fix_iter=1)
test_cfg = dict(metrics=('PSNR', 'SSIM'), crop_border=0)
test_cfg = mmcv.Config(test_cfg)
data_batch = {
'lq': inputs,
'gt': targets,
'meta': [{
'gt_path': 'fake_path/fake_name.png',
'key': '000'
}]
}
restorer = build_model(model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
if torch.cuda.is_available():
restorer = restorer.cuda()
with pytest.raises(AssertionError):
# evaluation with metrics must have gt images
restorer(lq=inputs, test_mode=True)
with tempfile.TemporaryDirectory() as tmpdir:
outputs = restorer(
**data_batch,
test_mode=True,
save_image=True,
save_path=tmpdir,
iteration=None)
assert isinstance(outputs, dict)
assert isinstance(outputs['eval_result'], dict)
assert isinstance(outputs['eval_result']['PSNR'], float)
assert isinstance(outputs['eval_result']['SSIM'], float)
outputs = restorer(
**data_batch,
test_mode=True,
save_image=True,
save_path=tmpdir,
iteration=100)
assert isinstance(outputs, dict)
assert isinstance(outputs['eval_result'], dict)
assert isinstance(outputs['eval_result']['PSNR'], float)
assert isinstance(outputs['eval_result']['SSIM'], float)
with pytest.raises(ValueError):
# iteration should be number or None
restorer(
**data_batch,
test_mode=True,
save_image=True,
save_path=tmpdir,
iteration='100')
# forward_test (with ensemble)
model_cfg = dict(
type='BasicVSR',
generator=dict(
type='BasicVSRNet',
mid_channels=64,
num_blocks=30,
spynet_pretrained=None),
pixel_loss=dict(type='MSELoss', loss_weight=1.0, reduction='sum'),
ensemble=dict(
type='SpatialTemporalEnsemble', is_temporal_ensemble=False),
)
train_cfg = dict(fix_iter=1)
train_cfg = mmcv.Config(train_cfg)
test_cfg = None
restorer = build_model(model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
inputs = torch.rand(1, 5, 3, 64, 64)
targets = torch.rand(1, 5, 3, 256, 256)
if torch.cuda.is_available():
inputs = inputs.cuda()
targets = targets.cuda()
restorer = restorer.cuda()
data_batch = {'lq': inputs, 'gt': targets}
with torch.no_grad():
outputs = restorer(**data_batch, test_mode=True)
assert torch.equal(outputs['lq'], data_batch['lq'].cpu())
assert torch.equal(outputs['gt'], data_batch['gt'].cpu())
assert torch.is_tensor(outputs['output'])
assert outputs['output'].size() == (1, 5, 3, 256, 256)
# forward_test (with unsupported ensemble)
model_cfg = dict(
type='BasicVSR',
generator=dict(
type='BasicVSRNet',
mid_channels=64,
num_blocks=30,
spynet_pretrained=None),
pixel_loss=dict(type='MSELoss', loss_weight=1.0, reduction='sum'),
ensemble=dict(type='abc', is_temporal_ensemble=False),
)
with pytest.raises(NotImplementedError):
restorer = build_model(
model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
| 6,854 | 32.602941 | 79 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_restorers/test_real_basicvsr.py | # Copyright (c) OpenMMLab. All rights reserved.
from unittest.mock import patch
import pytest
import torch
from mmcv.runner import obj_from_dict
from mmedit.models import build_model
from mmedit.models.backbones import RealBasicVSRNet
from mmedit.models.components import UNetDiscriminatorWithSpectralNorm
from mmedit.models.losses import GANLoss, L1Loss
def test_real_basicvsr():
model_cfg = dict(
type='RealBasicVSR',
generator=dict(type='RealBasicVSRNet'),
discriminator=dict(
type='UNetDiscriminatorWithSpectralNorm',
in_channels=3,
mid_channels=64,
skip_connection=True),
pixel_loss=dict(type='L1Loss', loss_weight=1.0, reduction='mean'),
cleaning_loss=dict(type='L1Loss', loss_weight=1.0, reduction='mean'),
gan_loss=dict(
type='GANLoss',
gan_type='vanilla',
loss_weight=1e-1,
real_label_val=1.0,
fake_label_val=0),
is_use_sharpened_gt_in_pixel=True,
is_use_sharpened_gt_in_percep=True,
is_use_sharpened_gt_in_gan=True,
is_use_ema=True,
)
train_cfg = None
test_cfg = None
# build restorer
restorer = build_model(model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
# test attributes
assert restorer.__class__.__name__ == 'RealBasicVSR'
assert isinstance(restorer.generator, RealBasicVSRNet)
assert isinstance(restorer.discriminator,
UNetDiscriminatorWithSpectralNorm)
assert isinstance(restorer.pixel_loss, L1Loss)
assert isinstance(restorer.gan_loss, GANLoss)
# prepare data
inputs = torch.rand(1, 5, 3, 64, 64)
targets = torch.rand(1, 5, 3, 256, 256)
data_batch = {'lq': inputs, 'gt': targets, 'gt_unsharp': targets}
# prepare optimizer
optim_cfg = dict(type='Adam', lr=2e-4, betas=(0.9, 0.999))
optimizer = {
'generator':
obj_from_dict(optim_cfg, torch.optim,
dict(
params=getattr(restorer, 'generator').parameters())),
'discriminator':
obj_from_dict(
optim_cfg, torch.optim,
dict(params=getattr(restorer, 'discriminator').parameters()))
}
# no forward train in GAN models, raise ValueError
with pytest.raises(ValueError):
restorer(**data_batch, test_mode=False)
# test train_step
with patch.object(
restorer,
'perceptual_loss',
return_value=(torch.tensor(1.0), torch.tensor(2.0))):
outputs = restorer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
for v in [
'loss_perceptual', 'loss_gan', 'loss_d_real', 'loss_d_fake',
'loss_pix', 'loss_clean'
]:
assert isinstance(outputs['log_vars'][v], float)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['lq'], data_batch['lq'])
assert torch.equal(outputs['results']['gt'], data_batch['gt'])
assert torch.is_tensor(outputs['results']['output'])
assert outputs['results']['output'].size() == (5, 3, 256, 256)
# test train_step (gpu)
if torch.cuda.is_available():
restorer = restorer.cuda()
optimizer = {
'generator':
obj_from_dict(
optim_cfg, torch.optim,
dict(params=getattr(restorer, 'generator').parameters())),
'discriminator':
obj_from_dict(
optim_cfg, torch.optim,
dict(params=getattr(restorer, 'discriminator').parameters()))
}
data_batch = {
'lq': inputs.cuda(),
'gt': targets.cuda(),
'gt_unsharp': targets.cuda()
}
# train_step
with patch.object(
restorer,
'perceptual_loss',
return_value=(torch.tensor(1.0).cuda(),
torch.tensor(2.0).cuda())):
outputs = restorer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
for v in [
'loss_perceptual', 'loss_gan', 'loss_d_real',
'loss_d_fake', 'loss_pix', 'loss_clean'
]:
assert isinstance(outputs['log_vars'][v], float)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['lq'],
data_batch['lq'].cpu())
assert torch.equal(outputs['results']['gt'],
data_batch['gt'].cpu())
assert torch.is_tensor(outputs['results']['output'])
assert outputs['results']['output'].size() == (5, 3, 256, 256)
# test disc_steps and disc_init_steps and start_iter
data_batch = {
'lq': inputs.cpu(),
'gt': targets.cpu(),
'gt_unsharp': targets.cpu()
}
train_cfg = dict(disc_steps=2, disc_init_steps=2, start_iter=0)
restorer = build_model(model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
with patch.object(
restorer,
'perceptual_loss',
return_value=(torch.tensor(1.0), torch.tensor(2.0))):
outputs = restorer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
for v in ['loss_d_real', 'loss_d_fake']:
assert isinstance(outputs['log_vars'][v], float)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['lq'], data_batch['lq'])
assert torch.equal(outputs['results']['gt'], data_batch['gt'])
assert torch.is_tensor(outputs['results']['output'])
assert outputs['results']['output'].size() == (5, 3, 256, 256)
# test without pixel loss and perceptual loss
model_cfg_ = model_cfg.copy()
model_cfg_.pop('pixel_loss')
restorer = build_model(model_cfg_, train_cfg=None, test_cfg=None)
outputs = restorer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
for v in ['loss_gan', 'loss_d_real', 'loss_d_fake']:
assert isinstance(outputs['log_vars'][v], float)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['lq'], data_batch['lq'])
assert torch.equal(outputs['results']['gt'], data_batch['gt'])
assert torch.is_tensor(outputs['results']['output'])
assert outputs['results']['output'].size() == (5, 3, 256, 256)
# test train_step w/o loss_percep
restorer = build_model(model_cfg, train_cfg=None, test_cfg=None)
with patch.object(
restorer, 'perceptual_loss',
return_value=(None, torch.tensor(2.0))):
outputs = restorer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
for v in [
'loss_style', 'loss_gan', 'loss_d_real', 'loss_d_fake',
'loss_pix', 'loss_clean'
]:
assert isinstance(outputs['log_vars'][v], float)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['lq'], data_batch['lq'])
assert torch.equal(outputs['results']['gt'], data_batch['gt'])
assert torch.is_tensor(outputs['results']['output'])
assert outputs['results']['output'].size() == (5, 3, 256, 256)
# test train_step w/o loss_style
restorer = build_model(model_cfg, train_cfg=None, test_cfg=None)
with patch.object(
restorer, 'perceptual_loss',
return_value=(torch.tensor(2.0), None)):
outputs = restorer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
for v in [
'loss_perceptual', 'loss_gan', 'loss_d_real', 'loss_d_fake',
'loss_pix', 'loss_clean'
]:
assert isinstance(outputs['log_vars'][v], float)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['lq'], data_batch['lq'])
assert torch.equal(outputs['results']['gt'], data_batch['gt'])
assert torch.is_tensor(outputs['results']['output'])
assert outputs['results']['output'].size() == (5, 3, 256, 256)
| 8,475 | 39.361905 | 79 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_restorers/test_tdan.py | # Copyright (c) OpenMMLab. All rights reserved.
import tempfile
import mmcv
import pytest
import torch
from mmcv.runner import obj_from_dict
from mmedit.models import build_model
from mmedit.models.backbones import TDANNet
from mmedit.models.losses import MSELoss
def test_tdan_model():
model_cfg = dict(
type='TDAN',
generator=dict(
type='TDANNet',
in_channels=3,
mid_channels=64,
out_channels=3,
num_blocks_before_align=5,
num_blocks_after_align=10),
pixel_loss=dict(type='MSELoss', loss_weight=1.0, reduction='sum'),
lq_pixel_loss=dict(type='MSELoss', loss_weight=1.0, reduction='sum'),
)
train_cfg = None
test_cfg = None
# build restorer
restorer = build_model(model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
# test attributes
assert restorer.__class__.__name__ == 'TDAN'
assert isinstance(restorer.generator, TDANNet)
assert isinstance(restorer.pixel_loss, MSELoss)
# prepare data
inputs = torch.rand(1, 5, 3, 8, 8)
targets = torch.rand(1, 3, 32, 32)
# test train_step and forward_test (gpu)
if torch.cuda.is_available():
restorer = restorer.cuda()
data_batch = {'lq': inputs.cuda(), 'gt': targets.cuda()}
# prepare optimizer
optim_cfg = dict(type='Adam', lr=2e-4, betas=(0.9, 0.999))
optimizer = {
'generator':
obj_from_dict(
optim_cfg, torch.optim,
dict(params=getattr(restorer, 'generator').parameters()))
}
# train_step
outputs = restorer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
assert isinstance(outputs['log_vars']['loss_pix'], float)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['lq'], data_batch['lq'].cpu())
assert torch.equal(outputs['results']['gt'], data_batch['gt'].cpu())
assert torch.is_tensor(outputs['results']['output'])
assert outputs['results']['output'].size() == (1, 3, 32, 32)
# test forward_dummy
with torch.no_grad():
output = restorer.forward_dummy(data_batch['lq'])
assert isinstance(output, tuple)
assert torch.is_tensor(output[0])
assert output[0].size() == (1, 3, 32, 32)
assert torch.is_tensor(output[1])
assert output[1].size() == (1, 5, 3, 8, 8)
# forward_test
with torch.no_grad():
outputs = restorer(**data_batch, test_mode=True)
assert torch.equal(outputs['lq'], data_batch['lq'].cpu())
assert torch.equal(outputs['gt'], data_batch['gt'].cpu())
assert torch.is_tensor(outputs['output'])
assert outputs['output'].size() == (1, 3, 32, 32)
with torch.no_grad():
outputs = restorer(inputs.cuda(), test_mode=True)
assert torch.equal(outputs['lq'], data_batch['lq'].cpu())
assert torch.is_tensor(outputs['output'])
assert outputs['output'].size() == (1, 3, 32, 32)
# test with metric and save image
if torch.cuda.is_available():
train_cfg = mmcv.ConfigDict(tsa_iter=1)
test_cfg = dict(metrics=('PSNR', 'SSIM'), crop_border=0)
test_cfg = mmcv.Config(test_cfg)
data_batch = {
'lq': inputs.cuda(),
'gt': targets.cuda(),
'meta': [{
'gt_path': 'fake_path/fake_name.png',
'key': '000/00000000'
}]
}
restorer = build_model(
model_cfg, train_cfg=train_cfg, test_cfg=test_cfg).cuda()
with pytest.raises(AssertionError):
# evaluation with metrics must have gt images
restorer(lq=inputs.cuda(), test_mode=True)
with tempfile.TemporaryDirectory() as tmpdir:
outputs = restorer(
**data_batch,
test_mode=True,
save_image=True,
save_path=tmpdir,
iteration=None)
assert isinstance(outputs, dict)
assert isinstance(outputs['eval_result'], dict)
assert isinstance(outputs['eval_result']['PSNR'], float)
assert isinstance(outputs['eval_result']['SSIM'], float)
outputs = restorer(
**data_batch,
test_mode=True,
save_image=True,
save_path=tmpdir,
iteration=100)
assert isinstance(outputs, dict)
assert isinstance(outputs['eval_result'], dict)
assert isinstance(outputs['eval_result']['PSNR'], float)
assert isinstance(outputs['eval_result']['SSIM'], float)
with pytest.raises(ValueError):
# iteration should be number or None
restorer(
**data_batch,
test_mode=True,
save_image=True,
save_path=tmpdir,
iteration='100')
| 5,090 | 34.110345 | 77 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_restorers/test_real_esrgan.py | # Copyright (c) OpenMMLab. All rights reserved.
from unittest.mock import patch
import pytest
import torch
from mmcv.runner import obj_from_dict
from mmedit.models import build_model
from mmedit.models.backbones import MSRResNet
from mmedit.models.components import ModifiedVGG
from mmedit.models.losses import GANLoss, L1Loss
def test_real_esrgan():
model_cfg = dict(
type='RealESRGAN',
generator=dict(
type='MSRResNet',
in_channels=3,
out_channels=3,
mid_channels=4,
num_blocks=1,
upscale_factor=4),
discriminator=dict(type='ModifiedVGG', in_channels=3, mid_channels=2),
pixel_loss=dict(type='L1Loss', loss_weight=1.0, reduction='mean'),
gan_loss=dict(
type='GANLoss',
gan_type='vanilla',
loss_weight=1e-1,
real_label_val=1.0,
fake_label_val=0),
is_use_sharpened_gt_in_pixel=True,
is_use_sharpened_gt_in_percep=True,
is_use_sharpened_gt_in_gan=True,
is_use_ema=True,
)
train_cfg = None
test_cfg = None
# build restorer
restorer = build_model(model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
# test attributes
assert restorer.__class__.__name__ == 'RealESRGAN'
assert isinstance(restorer.generator, MSRResNet)
assert isinstance(restorer.discriminator, ModifiedVGG)
assert isinstance(restorer.pixel_loss, L1Loss)
assert isinstance(restorer.gan_loss, GANLoss)
# prepare data
inputs = torch.rand(1, 3, 32, 32)
targets = torch.rand(1, 3, 128, 128)
data_batch = {'lq': inputs, 'gt': targets, 'gt_unsharp': targets}
# prepare optimizer
optim_cfg = dict(type='Adam', lr=2e-4, betas=(0.9, 0.999))
optimizer = {
'generator':
obj_from_dict(optim_cfg, torch.optim,
dict(
params=getattr(restorer, 'generator').parameters())),
'discriminator':
obj_from_dict(
optim_cfg, torch.optim,
dict(params=getattr(restorer, 'discriminator').parameters()))
}
# no forward train in GAN models, raise ValueError
with pytest.raises(ValueError):
restorer(**data_batch, test_mode=False)
# test forward_test
data_batch.pop('gt_unsharp')
with torch.no_grad():
outputs = restorer(**data_batch, test_mode=True)
assert torch.equal(outputs['lq'], data_batch['lq'])
assert torch.is_tensor(outputs['output'])
assert outputs['output'].size() == (1, 3, 128, 128)
# test forward_dummy
with torch.no_grad():
output = restorer.forward_dummy(data_batch['lq'])
assert torch.is_tensor(output)
assert output.size() == (1, 3, 128, 128)
# val_step
with torch.no_grad():
outputs = restorer.val_step(data_batch)
data_batch['gt_unsharp'] = targets
assert torch.equal(outputs['lq'], data_batch['lq'])
assert torch.is_tensor(outputs['output'])
assert outputs['output'].size() == (1, 3, 128, 128)
# test train_step
with patch.object(
restorer,
'perceptual_loss',
return_value=(torch.tensor(1.0), torch.tensor(2.0))):
outputs = restorer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
for v in [
'loss_perceptual', 'loss_gan', 'loss_d_real', 'loss_d_fake',
'loss_pix'
]:
assert isinstance(outputs['log_vars'][v], float)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['lq'], data_batch['lq'])
assert torch.equal(outputs['results']['gt'], data_batch['gt'])
assert torch.is_tensor(outputs['results']['output'])
assert outputs['results']['output'].size() == (1, 3, 128, 128)
# test train_step and forward_test (gpu)
if torch.cuda.is_available():
restorer = restorer.cuda()
optimizer = {
'generator':
obj_from_dict(
optim_cfg, torch.optim,
dict(params=getattr(restorer, 'generator').parameters())),
'discriminator':
obj_from_dict(
optim_cfg, torch.optim,
dict(params=getattr(restorer, 'discriminator').parameters()))
}
data_batch = {
'lq': inputs.cuda(),
'gt': targets.cuda(),
'gt_unsharp': targets.cuda()
}
# forward_test
data_batch.pop('gt_unsharp')
with torch.no_grad():
outputs = restorer(**data_batch, test_mode=True)
assert torch.equal(outputs['lq'], data_batch['lq'].cpu())
assert torch.is_tensor(outputs['output'])
assert outputs['output'].size() == (1, 3, 128, 128)
# val_step
with torch.no_grad():
outputs = restorer.val_step(data_batch)
data_batch['gt_unsharp'] = targets.cuda()
assert torch.equal(outputs['lq'], data_batch['lq'].cpu())
assert torch.is_tensor(outputs['output'])
assert outputs['output'].size() == (1, 3, 128, 128)
# train_step
with patch.object(
restorer,
'perceptual_loss',
return_value=(torch.tensor(1.0).cuda(),
torch.tensor(2.0).cuda())):
outputs = restorer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
for v in [
'loss_perceptual', 'loss_gan', 'loss_d_real',
'loss_d_fake', 'loss_pix'
]:
assert isinstance(outputs['log_vars'][v], float)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['lq'],
data_batch['lq'].cpu())
assert torch.equal(outputs['results']['gt'],
data_batch['gt'].cpu())
assert torch.is_tensor(outputs['results']['output'])
assert outputs['results']['output'].size() == (1, 3, 128, 128)
# test disc_steps and disc_init_steps and start_iter
data_batch = {
'lq': inputs.cpu(),
'gt': targets.cpu(),
'gt_unsharp': targets.cpu()
}
train_cfg = dict(disc_steps=2, disc_init_steps=2, start_iter=0)
restorer = build_model(model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
with patch.object(
restorer,
'perceptual_loss',
return_value=(torch.tensor(1.0), torch.tensor(2.0))):
outputs = restorer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
for v in ['loss_d_real', 'loss_d_fake']:
assert isinstance(outputs['log_vars'][v], float)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['lq'], data_batch['lq'])
assert torch.equal(outputs['results']['gt'], data_batch['gt'])
assert torch.is_tensor(outputs['results']['output'])
assert outputs['results']['output'].size() == (1, 3, 128, 128)
# test no discriminator (testing mode)
model_cfg_ = model_cfg.copy()
model_cfg_.pop('discriminator')
restorer = build_model(model_cfg_, train_cfg=train_cfg, test_cfg=test_cfg)
data_batch.pop('gt_unsharp')
with torch.no_grad():
outputs = restorer(**data_batch, test_mode=True)
data_batch['gt_unsharp'] = targets.cpu()
assert torch.equal(outputs['lq'], data_batch['lq'])
assert torch.is_tensor(outputs['output'])
assert outputs['output'].size() == (1, 3, 128, 128)
# test without pixel loss and perceptual loss
model_cfg_ = model_cfg.copy()
model_cfg_.pop('pixel_loss')
restorer = build_model(model_cfg_, train_cfg=None, test_cfg=None)
outputs = restorer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
for v in ['loss_gan', 'loss_d_real', 'loss_d_fake']:
assert isinstance(outputs['log_vars'][v], float)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['lq'], data_batch['lq'])
assert torch.equal(outputs['results']['gt'], data_batch['gt'])
assert torch.is_tensor(outputs['results']['output'])
assert outputs['results']['output'].size() == (1, 3, 128, 128)
# test train_step w/o loss_percep
restorer = build_model(model_cfg, train_cfg=None, test_cfg=None)
with patch.object(
restorer, 'perceptual_loss',
return_value=(None, torch.tensor(2.0))):
outputs = restorer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
for v in [
'loss_style', 'loss_gan', 'loss_d_real', 'loss_d_fake',
'loss_pix'
]:
assert isinstance(outputs['log_vars'][v], float)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['lq'], data_batch['lq'])
assert torch.equal(outputs['results']['gt'], data_batch['gt'])
assert torch.is_tensor(outputs['results']['output'])
assert outputs['results']['output'].size() == (1, 3, 128, 128)
# test train_step w/o loss_style
restorer = build_model(model_cfg, train_cfg=None, test_cfg=None)
with patch.object(
restorer, 'perceptual_loss',
return_value=(torch.tensor(2.0), None)):
outputs = restorer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
for v in [
'loss_perceptual', 'loss_gan', 'loss_d_real', 'loss_d_fake',
'loss_pix'
]:
assert isinstance(outputs['log_vars'][v], float)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['lq'], data_batch['lq'])
assert torch.equal(outputs['results']['gt'], data_batch['gt'])
assert torch.is_tensor(outputs['results']['output'])
assert outputs['results']['output'].size() == (1, 3, 128, 128)
| 10,264 | 38.480769 | 79 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_restorers/test_glean.py | # Copyright (c) OpenMMLab. All rights reserved.
import mmcv
import pytest
import torch
from mmedit.models import build_model
def test_glean():
model_cfg = dict(
type='GLEAN',
generator=dict(
type='GLEANStyleGANv2',
in_size=16,
out_size=64,
style_channels=512),
discriminator=dict(type='StyleGAN2Discriminator', in_size=64),
pixel_loss=dict(type='L1Loss', loss_weight=1.0, reduction='mean'),
gan_loss=dict(
type='GANLoss',
gan_type='vanilla',
real_label_val=1.0,
fake_label_val=0,
loss_weight=5e-3))
train_cfg = None
test_cfg = mmcv.Config(dict(metrics=['PSNR'], crop_border=0))
# build restorer
restorer = build_model(model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
# prepare data
inputs = torch.rand(1, 3, 16, 16)
targets = torch.rand(1, 3, 64, 64)
data_batch = {'lq': inputs, 'gt': targets}
restorer = build_model(model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
meta = [{'lq_path': ''}]
# test forward_test (cpu)
with pytest.raises(ValueError): # iteration is not None or number
with torch.no_grad():
restorer(
**data_batch,
test_mode=True,
save_image=True,
meta=meta,
iteration='1')
with pytest.raises(AssertionError): # test with metric but gt is None
with torch.no_grad():
data_batch.pop('gt')
restorer(**data_batch, test_mode=True)
# test forward_test (gpu)
if torch.cuda.is_available():
data_batch = {'lq': inputs.cuda(), 'gt': targets.cuda()}
restorer = restorer.cuda()
with pytest.raises(ValueError): # iteration is not None or number
with torch.no_grad():
restorer(
**data_batch,
test_mode=True,
save_image=True,
meta=meta,
iteration='1')
with pytest.raises(AssertionError): # test with metric but gt is None
with torch.no_grad():
data_batch.pop('gt')
restorer(**data_batch, test_mode=True)
| 2,269 | 30.971831 | 78 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_restorers/test_liif.py | # Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
import torch
import torch.nn as nn
from mmcv.runner import obj_from_dict
from mmcv.utils.config import Config
from mmedit.models import build_model
from mmedit.models.registry import COMPONENTS
@COMPONENTS.register_module()
class BP(nn.Module):
"""A simple BP network for testing LIIF.
Args:
in_dim (int): Input dimension.
out_dim (int): Output dimension.
"""
def __init__(self, in_dim, out_dim):
super().__init__()
self.layer = nn.Linear(in_dim, out_dim)
def forward(self, x):
shape = x.shape[:-1]
x = self.layer(x.view(-1, x.shape[-1]))
return x.view(*shape, -1)
def test_liif():
model_cfg = dict(
type='LIIF',
generator=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),
rgb_mean=(0.4488, 0.4371, 0.4040),
rgb_std=(1., 1., 1.),
pixel_loss=dict(type='L1Loss', loss_weight=1.0, reduction='mean'))
scale_max = 4
train_cfg = None
test_cfg = Config(dict(metrics=['PSNR', 'SSIM'], crop_border=scale_max))
# build restorer
restorer = build_model(model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
# test attributes
assert restorer.__class__.__name__ == 'LIIF'
# prepare data
inputs = torch.rand(1, 3, 22, 11)
targets = torch.rand(1, 128 * 64, 3)
coord = torch.rand(1, 128 * 64, 2)
cell = torch.rand(1, 128 * 64, 2)
data_batch = {'lq': inputs, 'gt': targets, 'coord': coord, 'cell': cell}
# prepare optimizer
optim_cfg = dict(type='Adam', lr=1e-4, betas=(0.9, 0.999))
optimizer = obj_from_dict(optim_cfg, torch.optim,
dict(params=restorer.parameters()))
# test train_step and forward_test (cpu)
outputs = restorer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
assert isinstance(outputs['log_vars']['loss_pix'], float)
assert outputs['num_samples'] == 1
assert outputs['results']['lq'].shape == data_batch['lq'].shape
assert outputs['results']['gt'].shape == data_batch['gt'].shape
assert torch.is_tensor(outputs['results']['output'])
assert outputs['results']['output'].size() == (1, 128 * 64, 3)
# test train_step and forward_test (gpu)
if torch.cuda.is_available():
restorer = restorer.cuda()
data_batch = {
'lq': inputs.cuda(),
'gt': targets.cuda(),
'coord': coord.cuda(),
'cell': cell.cuda()
}
# train_step
optimizer = obj_from_dict(optim_cfg, torch.optim,
dict(params=restorer.parameters()))
outputs = restorer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
assert isinstance(outputs['log_vars']['loss_pix'], float)
assert outputs['num_samples'] == 1
assert outputs['results']['lq'].shape == data_batch['lq'].shape
assert outputs['results']['gt'].shape == data_batch['gt'].shape
assert torch.is_tensor(outputs['results']['output'])
assert outputs['results']['output'].size() == (1, 128 * 64, 3)
# val_step
result = restorer.val_step(data_batch, meta=[{'gt_path': ''}])
assert isinstance(result, dict)
assert isinstance(result['eval_result'], dict)
assert result['eval_result'].keys() == set({'PSNR', 'SSIM'})
assert isinstance(result['eval_result']['PSNR'], np.float64)
assert isinstance(result['eval_result']['SSIM'], np.float64)
| 4,114 | 33.579832 | 77 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_restorers/test_dic_model.py | # Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
import pytest
import torch
from mmcv.runner import obj_from_dict
from mmcv.utils.config import Config
from mmedit.models.builder import build_model
def test_dic_model():
pretrained = 'https://download.openmmlab.com/mmediting/' + \
'restorers/dic/light_cnn_feature.pth'
model_cfg_pre = dict(
type='DIC',
generator=dict(
type='DICNet', in_channels=3, out_channels=3, mid_channels=48),
pixel_loss=dict(type='L1Loss', loss_weight=1.0, reduction='mean'),
align_loss=dict(type='MSELoss', loss_weight=0.1, reduction='mean'))
model_cfg = dict(
type='DIC',
generator=dict(
type='DICNet', in_channels=3, out_channels=3, mid_channels=48),
discriminator=dict(type='LightCNN', in_channels=3),
pixel_loss=dict(type='L1Loss', loss_weight=1.0, reduction='mean'),
align_loss=dict(type='MSELoss', loss_weight=0.1, reduction='mean'),
feature_loss=dict(
type='LightCNNFeatureLoss',
pretrained=pretrained,
loss_weight=0.1,
criterion='l1'),
gan_loss=dict(
type='GANLoss',
gan_type='vanilla',
loss_weight=0.005,
real_label_val=1.0,
fake_label_val=0))
scale = 8
train_cfg = None
test_cfg = Config(dict(metrics=['PSNR', 'SSIM'], crop_border=scale))
# build restorer
build_model(model_cfg_pre, train_cfg=train_cfg, test_cfg=test_cfg)
restorer = build_model(model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
# test attributes
assert restorer.__class__.__name__ == 'DIC'
# prepare data
inputs = torch.rand(1, 3, 16, 16)
targets = torch.rand(1, 3, 128, 128)
heatmap = torch.rand(1, 68, 32, 32)
data_batch = {'lq': inputs, 'gt': targets, 'heatmap': heatmap}
# prepare optimizer
optim_cfg = dict(type='Adam', lr=1e-4, betas=(0.9, 0.999))
generator = obj_from_dict(optim_cfg, torch.optim,
dict(params=restorer.parameters()))
discriminator = obj_from_dict(optim_cfg, torch.optim,
dict(params=restorer.parameters()))
optimizer = dict(generator=generator, discriminator=discriminator)
# test train_step and forward_test (cpu)
outputs = restorer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
assert isinstance(outputs['log_vars']['loss_pixel_v3'], float)
assert outputs['num_samples'] == 1
assert outputs['results']['lq'].shape == data_batch['lq'].shape
assert outputs['results']['gt'].shape == data_batch['gt'].shape
assert torch.is_tensor(outputs['results']['output'])
assert outputs['results']['output'].size() == (1, 3, 128, 128)
# test train_step and forward_test (gpu)
if torch.cuda.is_available():
restorer = restorer.cuda()
data_batch = {
'lq': inputs.cuda(),
'gt': targets.cuda(),
'heatmap': heatmap.cuda()
}
# train_step
optim_cfg = dict(type='Adam', lr=1e-4, betas=(0.9, 0.999))
generator = obj_from_dict(optim_cfg, torch.optim,
dict(params=restorer.parameters()))
discriminator = obj_from_dict(optim_cfg, torch.optim,
dict(params=restorer.parameters()))
optimizer = dict(generator=generator, discriminator=discriminator)
outputs = restorer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
assert isinstance(outputs['log_vars']['loss_pixel_v3'], float)
assert outputs['num_samples'] == 1
assert outputs['results']['lq'].shape == data_batch['lq'].shape
assert outputs['results']['gt'].shape == data_batch['gt'].shape
assert torch.is_tensor(outputs['results']['output'])
assert outputs['results']['output'].size() == (1, 3, 128, 128)
# val_step
data_batch.pop('heatmap')
result = restorer.val_step(data_batch, meta=[{'gt_path': ''}])
assert isinstance(result, dict)
assert isinstance(result['eval_result'], dict)
assert result['eval_result'].keys() == set({'PSNR', 'SSIM'})
assert isinstance(result['eval_result']['PSNR'], np.float64)
assert isinstance(result['eval_result']['SSIM'], np.float64)
with pytest.raises(AssertionError):
# evaluation with metrics must have gt images
restorer(lq=inputs.cuda(), test_mode=True)
with pytest.raises(TypeError):
restorer.init_weights(pretrained=1)
with pytest.raises(OSError):
restorer.init_weights(pretrained='')
| 4,844 | 39.375 | 77 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_restorers/test_ttsr.py | # Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
import torch
from mmcv.runner import obj_from_dict
from mmcv.utils.config import Config
from mmedit.models import build_backbone, build_model
from mmedit.models.backbones.sr_backbones.ttsr_net import (CSFI2, CSFI3, SFE,
MergeFeatures)
def test_sfe():
inputs = torch.rand(2, 3, 48, 48)
sfe = SFE(3, 64, 16, 1.)
outputs = sfe(inputs)
assert outputs.shape == (2, 64, 48, 48)
def test_csfi():
inputs1 = torch.rand(2, 16, 24, 24)
inputs2 = torch.rand(2, 16, 48, 48)
inputs4 = torch.rand(2, 16, 96, 96)
csfi2 = CSFI2(mid_channels=16)
out1, out2 = csfi2(inputs1, inputs2)
assert out1.shape == (2, 16, 24, 24)
assert out2.shape == (2, 16, 48, 48)
csfi3 = CSFI3(mid_channels=16)
out1, out2, out4 = csfi3(inputs1, inputs2, inputs4)
assert out1.shape == (2, 16, 24, 24)
assert out2.shape == (2, 16, 48, 48)
assert out4.shape == (2, 16, 96, 96)
def test_merge_features():
inputs1 = torch.rand(2, 16, 24, 24)
inputs2 = torch.rand(2, 16, 48, 48)
inputs4 = torch.rand(2, 16, 96, 96)
merge_features = MergeFeatures(mid_channels=16, out_channels=3)
out = merge_features(inputs1, inputs2, inputs4)
assert out.shape == (2, 3, 96, 96)
def test_ttsr_net():
inputs = torch.rand(2, 3, 24, 24)
soft_attention = torch.rand(2, 1, 24, 24)
t_level3 = torch.rand(2, 64, 24, 24)
t_level2 = torch.rand(2, 32, 48, 48)
t_level1 = torch.rand(2, 16, 96, 96)
ttsr_cfg = dict(
type='TTSRNet',
in_channels=3,
out_channels=3,
mid_channels=16,
texture_channels=16)
ttsr = build_backbone(ttsr_cfg)
outputs = ttsr(inputs, soft_attention, (t_level3, t_level2, t_level1))
assert outputs.shape == (2, 3, 96, 96)
def test_ttsr():
model_cfg = dict(
type='TTSR',
generator=dict(
type='TTSRNet',
in_channels=3,
out_channels=3,
mid_channels=64,
num_blocks=(16, 16, 8, 4)),
extractor=dict(type='LTE', load_pretrained_vgg=False),
transformer=dict(type='SearchTransformer'),
discriminator=dict(type='TTSRDiscriminator', in_size=64),
pixel_loss=dict(type='L1Loss', loss_weight=1.0, reduction='mean'),
perceptual_loss=dict(
type='PerceptualLoss',
layer_weights={'29': 1.0},
vgg_type='vgg19',
perceptual_weight=1e-2,
style_weight=0.001,
criterion='mse'),
transferal_perceptual_loss=dict(
type='TransferalPerceptualLoss',
loss_weight=1e-2,
use_attention=False,
criterion='mse'),
gan_loss=dict(
type='GANLoss',
gan_type='vanilla',
loss_weight=1e-3,
real_label_val=1.0,
fake_label_val=0))
scale = 4
train_cfg = None
test_cfg = Config(dict(metrics=['PSNR', 'SSIM'], crop_border=scale))
# build restorer
restorer = build_model(model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
model_cfg = dict(
type='TTSR',
generator=dict(
type='TTSRNet',
in_channels=3,
out_channels=3,
mid_channels=64,
num_blocks=(16, 16, 8, 4)),
extractor=dict(type='LTE'),
transformer=dict(type='SearchTransformer'),
discriminator=dict(type='TTSRDiscriminator', in_size=64),
pixel_loss=dict(type='L1Loss', loss_weight=1.0, reduction='mean'),
perceptual_loss=dict(
type='PerceptualLoss',
layer_weights={'29': 1.0},
vgg_type='vgg19',
perceptual_weight=1e-2,
style_weight=0.001,
criterion='mse'),
transferal_perceptual_loss=dict(
type='TransferalPerceptualLoss',
loss_weight=1e-2,
use_attention=False,
criterion='mse'),
gan_loss=dict(
type='GANLoss',
gan_type='vanilla',
loss_weight=1e-3,
real_label_val=1.0,
fake_label_val=0))
scale = 4
train_cfg = None
test_cfg = Config(dict(metrics=['PSNR', 'SSIM'], crop_border=scale))
# build restorer
restorer = build_model(model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
# test attributes
assert restorer.__class__.__name__ == 'TTSR'
# prepare data
inputs = torch.rand(1, 3, 16, 16)
targets = torch.rand(1, 3, 64, 64)
ref = torch.rand(1, 3, 64, 64)
data_batch = {
'lq': inputs,
'gt': targets,
'ref': ref,
'lq_up': ref,
'ref_downup': ref
}
# prepare optimizer
optim_cfg_g = dict(type='Adam', lr=1e-4, betas=(0.9, 0.999))
optim_cfg_d = dict(type='Adam', lr=1e-4, betas=(0.9, 0.999))
optimizer = dict(
generator=obj_from_dict(optim_cfg_g, torch.optim,
dict(params=restorer.parameters())),
discriminator=obj_from_dict(optim_cfg_d, torch.optim,
dict(params=restorer.parameters())))
# test train_step and forward_test (cpu)
outputs = restorer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
assert isinstance(outputs['log_vars']['loss_pix'], float)
assert outputs['num_samples'] == 1
assert outputs['results']['lq'].shape == data_batch['lq'].shape
assert outputs['results']['gt'].shape == data_batch['gt'].shape
assert torch.is_tensor(outputs['results']['output'])
assert outputs['results']['output'].size() == (1, 3, 64, 64)
# test train_step and forward_test (gpu)
if torch.cuda.is_available():
restorer = restorer.cuda()
data_batch = {
'lq': inputs.cuda(),
'gt': targets.cuda(),
'ref': ref.cuda(),
'lq_up': ref.cuda(),
'ref_downup': ref.cuda()
}
# train_step
optimizer = dict(
generator=obj_from_dict(optim_cfg_g, torch.optim,
dict(params=restorer.parameters())),
discriminator=obj_from_dict(optim_cfg_d, torch.optim,
dict(params=restorer.parameters())))
outputs = restorer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
assert isinstance(outputs['log_vars']['loss_pix'], float)
assert outputs['num_samples'] == 1
assert outputs['results']['lq'].shape == data_batch['lq'].shape
assert outputs['results']['gt'].shape == data_batch['gt'].shape
assert torch.is_tensor(outputs['results']['output'])
assert outputs['results']['output'].size() == (1, 3, 64, 64)
# val_step
result = restorer.val_step(data_batch, meta=[{'gt_path': ''}])
assert isinstance(result, dict)
assert isinstance(result['eval_result'], dict)
assert result['eval_result'].keys() == set({'PSNR', 'SSIM'})
assert isinstance(result['eval_result']['PSNR'], np.float64)
assert isinstance(result['eval_result']['SSIM'], np.float64)
| 7,308 | 33.63981 | 77 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_restorers/test_esrgan.py | # Copyright (c) OpenMMLab. All rights reserved.
from unittest.mock import patch
import torch
from mmcv.runner import obj_from_dict
from mmedit.models import build_model
from mmedit.models.backbones import MSRResNet
from mmedit.models.components import ModifiedVGG
from mmedit.models.losses import GANLoss, L1Loss
def test_esrgan():
model_cfg = dict(
type='ESRGAN',
generator=dict(
type='MSRResNet',
in_channels=3,
out_channels=3,
mid_channels=4,
num_blocks=1,
upscale_factor=4),
discriminator=dict(type='ModifiedVGG', in_channels=3, mid_channels=2),
pixel_loss=dict(type='L1Loss', loss_weight=1.0, reduction='mean'),
gan_loss=dict(
type='GANLoss',
gan_type='vanilla',
real_label_val=1.0,
fake_label_val=0,
loss_weight=5e-3))
train_cfg = None
test_cfg = None
# build restorer
restorer = build_model(model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
# test attributes
assert restorer.__class__.__name__ == 'ESRGAN'
assert isinstance(restorer.generator, MSRResNet)
assert isinstance(restorer.discriminator, ModifiedVGG)
assert isinstance(restorer.pixel_loss, L1Loss)
assert isinstance(restorer.gan_loss, GANLoss)
# prepare data
inputs = torch.rand(1, 3, 32, 32)
targets = torch.rand(1, 3, 128, 128)
data_batch = {'lq': inputs, 'gt': targets}
# prepare optimizer
optim_cfg = dict(type='Adam', lr=2e-4, betas=(0.9, 0.999))
optimizer = {
'generator':
obj_from_dict(optim_cfg, torch.optim,
dict(
params=getattr(restorer, 'generator').parameters())),
'discriminator':
obj_from_dict(
optim_cfg, torch.optim,
dict(params=getattr(restorer, 'discriminator').parameters()))
}
# test train_step
with patch.object(
restorer,
'perceptual_loss',
return_value=(torch.tensor(1.0), torch.tensor(2.0))):
outputs = restorer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
for v in [
'loss_perceptual', 'loss_gan', 'loss_d_real', 'loss_d_fake',
'loss_pix'
]:
assert isinstance(outputs['log_vars'][v], float)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['lq'], data_batch['lq'])
assert torch.equal(outputs['results']['gt'], data_batch['gt'])
assert torch.is_tensor(outputs['results']['output'])
assert outputs['results']['output'].size() == (1, 3, 128, 128)
# test train_step and forward_test (gpu)
if torch.cuda.is_available():
restorer = restorer.cuda()
optimizer = {
'generator':
obj_from_dict(
optim_cfg, torch.optim,
dict(params=getattr(restorer, 'generator').parameters())),
'discriminator':
obj_from_dict(
optim_cfg, torch.optim,
dict(params=getattr(restorer, 'discriminator').parameters()))
}
data_batch = {'lq': inputs.cuda(), 'gt': targets.cuda()}
# train_step
with patch.object(
restorer,
'perceptual_loss',
return_value=(torch.tensor(1.0).cuda(),
torch.tensor(2.0).cuda())):
outputs = restorer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
for v in [
'loss_perceptual', 'loss_gan', 'loss_d_real',
'loss_d_fake', 'loss_pix'
]:
assert isinstance(outputs['log_vars'][v], float)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['lq'],
data_batch['lq'].cpu())
assert torch.equal(outputs['results']['gt'],
data_batch['gt'].cpu())
assert torch.is_tensor(outputs['results']['output'])
assert outputs['results']['output'].size() == (1, 3, 128, 128)
# test disc_steps and disc_init_steps
data_batch = {'lq': inputs.cpu(), 'gt': targets.cpu()}
train_cfg = dict(disc_steps=2, disc_init_steps=2)
restorer = build_model(model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
with patch.object(
restorer,
'perceptual_loss',
return_value=(torch.tensor(1.0), torch.tensor(2.0))):
outputs = restorer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
for v in ['loss_d_real', 'loss_d_fake']:
assert isinstance(outputs['log_vars'][v], float)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['lq'], data_batch['lq'])
assert torch.equal(outputs['results']['gt'], data_batch['gt'])
assert torch.is_tensor(outputs['results']['output'])
assert outputs['results']['output'].size() == (1, 3, 128, 128)
# test without pixel loss and perceptual loss
model_cfg_ = model_cfg.copy()
model_cfg_.pop('pixel_loss')
restorer = build_model(model_cfg_, train_cfg=None, test_cfg=None)
outputs = restorer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
for v in ['loss_gan', 'loss_d_real', 'loss_d_fake']:
assert isinstance(outputs['log_vars'][v], float)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['lq'], data_batch['lq'])
assert torch.equal(outputs['results']['gt'], data_batch['gt'])
assert torch.is_tensor(outputs['results']['output'])
assert outputs['results']['output'].size() == (1, 3, 128, 128)
# test train_step w/o loss_percep
restorer = build_model(model_cfg, train_cfg=None, test_cfg=None)
with patch.object(
restorer, 'perceptual_loss',
return_value=(None, torch.tensor(2.0))):
outputs = restorer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
for v in [
'loss_style', 'loss_gan', 'loss_d_real', 'loss_d_fake',
'loss_pix'
]:
assert isinstance(outputs['log_vars'][v], float)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['lq'], data_batch['lq'])
assert torch.equal(outputs['results']['gt'], data_batch['gt'])
assert torch.is_tensor(outputs['results']['output'])
assert outputs['results']['output'].size() == (1, 3, 128, 128)
# test train_step w/o loss_style
restorer = build_model(model_cfg, train_cfg=None, test_cfg=None)
with patch.object(
restorer, 'perceptual_loss',
return_value=(torch.tensor(2.0), None)):
outputs = restorer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
for v in [
'loss_perceptual', 'loss_gan', 'loss_d_real', 'loss_d_fake',
'loss_pix'
]:
assert isinstance(outputs['log_vars'][v], float)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['lq'], data_batch['lq'])
assert torch.equal(outputs['results']['gt'], data_batch['gt'])
assert torch.is_tensor(outputs['results']['output'])
assert outputs['results']['output'].size() == (1, 3, 128, 128)
| 7,807 | 39.666667 | 79 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_restorers/test_edvr_model.py | # Copyright (c) OpenMMLab. All rights reserved.
import tempfile
import mmcv
import pytest
import torch
from mmcv.runner import obj_from_dict
from mmedit.models import build_model
from mmedit.models.backbones import EDVRNet
from mmedit.models.losses import L1Loss
def test_edvr_model():
model_cfg = dict(
type='EDVR',
generator=dict(
type='EDVRNet',
in_channels=3,
out_channels=3,
mid_channels=8,
num_frames=5,
deform_groups=2,
num_blocks_extraction=1,
num_blocks_reconstruction=1,
center_frame_idx=2,
with_tsa=False),
pixel_loss=dict(type='L1Loss', loss_weight=1.0, reduction='sum'),
)
train_cfg = None
test_cfg = None
# build restorer
restorer = build_model(model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
# test attributes
assert restorer.__class__.__name__ == 'EDVR'
assert isinstance(restorer.generator, EDVRNet)
assert isinstance(restorer.pixel_loss, L1Loss)
# prepare data
inputs = torch.rand(1, 5, 3, 8, 8)
targets = torch.rand(1, 3, 32, 32)
# test train_step and forward_test (gpu)
if torch.cuda.is_available():
restorer = restorer.cuda()
data_batch = {'lq': inputs.cuda(), 'gt': targets.cuda()}
# prepare optimizer
optim_cfg = dict(type='Adam', lr=2e-4, betas=(0.9, 0.999))
optimizer = {
'generator':
obj_from_dict(
optim_cfg, torch.optim,
dict(params=getattr(restorer, 'generator').parameters()))
}
# train_step
outputs = restorer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
assert isinstance(outputs['log_vars']['loss_pix'], float)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['lq'], data_batch['lq'].cpu())
assert torch.equal(outputs['results']['gt'], data_batch['gt'].cpu())
assert torch.is_tensor(outputs['results']['output'])
assert outputs['results']['output'].size() == (1, 3, 32, 32)
# with TSA
model_cfg['generator']['with_tsa'] = True
with pytest.raises(KeyError):
# In TSA mode, train_cfg must contain "tsa_iter"
train_cfg = dict(other_conent='xxx')
restorer = build_model(
model_cfg, train_cfg=train_cfg, test_cfg=test_cfg).cuda()
outputs = restorer.train_step(data_batch, optimizer)
train_cfg = None
restorer = build_model(
model_cfg, train_cfg=train_cfg, test_cfg=test_cfg).cuda()
outputs = restorer.train_step(data_batch, optimizer)
train_cfg = mmcv.ConfigDict(tsa_iter=1)
restorer = build_model(
model_cfg, train_cfg=train_cfg, test_cfg=test_cfg).cuda()
optimizer = {
'generator':
obj_from_dict(
optim_cfg, torch.optim,
dict(params=getattr(restorer, 'generator').parameters()))
}
# train without updating tsa module
outputs = restorer.train_step(data_batch, optimizer)
# train with updating tsa module
outputs = restorer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
assert isinstance(outputs['log_vars']['loss_pix'], float)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['lq'], data_batch['lq'].cpu())
assert torch.equal(outputs['results']['gt'], data_batch['gt'].cpu())
assert torch.is_tensor(outputs['results']['output'])
assert outputs['results']['output'].size() == (1, 3, 32, 32)
# test forward_dummy
with torch.no_grad():
output = restorer.forward_dummy(data_batch['lq'])
assert torch.is_tensor(output)
assert output.size() == (1, 3, 32, 32)
# forward_test
with torch.no_grad():
outputs = restorer(**data_batch, test_mode=True)
assert torch.equal(outputs['lq'], data_batch['lq'].cpu())
assert torch.equal(outputs['gt'], data_batch['gt'].cpu())
assert torch.is_tensor(outputs['output'])
assert outputs['output'].size() == (1, 3, 32, 32)
with torch.no_grad():
outputs = restorer(inputs.cuda(), test_mode=True)
assert torch.equal(outputs['lq'], data_batch['lq'].cpu())
assert torch.is_tensor(outputs['output'])
assert outputs['output'].size() == (1, 3, 32, 32)
# test with metric and save image
if torch.cuda.is_available():
train_cfg = mmcv.ConfigDict(tsa_iter=1)
test_cfg = dict(metrics=('PSNR', 'SSIM'), crop_border=0)
test_cfg = mmcv.Config(test_cfg)
data_batch = {
'lq': inputs.cuda(),
'gt': targets.cuda(),
'meta': [{
'gt_path': 'fake_path/fake_name.png',
'key': '000/00000000'
}]
}
restorer = build_model(
model_cfg, train_cfg=train_cfg, test_cfg=test_cfg).cuda()
with pytest.raises(AssertionError):
# evaluation with metrics must have gt images
restorer(lq=inputs.cuda(), test_mode=True)
with tempfile.TemporaryDirectory() as tmpdir:
outputs = restorer(
**data_batch,
test_mode=True,
save_image=True,
save_path=tmpdir,
iteration=None)
assert isinstance(outputs, dict)
assert isinstance(outputs['eval_result'], dict)
assert isinstance(outputs['eval_result']['PSNR'], float)
assert isinstance(outputs['eval_result']['SSIM'], float)
outputs = restorer(
**data_batch,
test_mode=True,
save_image=True,
save_path=tmpdir,
iteration=100)
assert isinstance(outputs, dict)
assert isinstance(outputs['eval_result'], dict)
assert isinstance(outputs['eval_result']['PSNR'], float)
assert isinstance(outputs['eval_result']['SSIM'], float)
with pytest.raises(ValueError):
# iteration should be number or None
restorer(
**data_batch,
test_mode=True,
save_image=True,
save_path=tmpdir,
iteration='100')
| 6,625 | 35.406593 | 77 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_restorers/test_srgan.py | # Copyright (c) OpenMMLab. All rights reserved.
from unittest.mock import patch
import pytest
import torch
from mmcv.runner import obj_from_dict
from mmedit.models import build_model
from mmedit.models.backbones import MSRResNet
from mmedit.models.components import ModifiedVGG
from mmedit.models.losses import GANLoss, L1Loss
def test_srgan():
model_cfg = dict(
type='SRGAN',
generator=dict(
type='MSRResNet',
in_channels=3,
out_channels=3,
mid_channels=4,
num_blocks=1,
upscale_factor=4),
discriminator=dict(type='ModifiedVGG', in_channels=3, mid_channels=2),
pixel_loss=dict(type='L1Loss', loss_weight=1.0, reduction='mean'),
gan_loss=dict(
type='GANLoss',
gan_type='vanilla',
real_label_val=1.0,
fake_label_val=0,
loss_weight=5e-3))
train_cfg = None
test_cfg = None
# build restorer
restorer = build_model(model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
# test attributes
assert restorer.__class__.__name__ == 'SRGAN'
assert isinstance(restorer.generator, MSRResNet)
assert isinstance(restorer.discriminator, ModifiedVGG)
assert isinstance(restorer.pixel_loss, L1Loss)
assert isinstance(restorer.gan_loss, GANLoss)
# prepare data
inputs = torch.rand(1, 3, 32, 32)
targets = torch.rand(1, 3, 128, 128)
data_batch = {'lq': inputs, 'gt': targets}
# prepare optimizer
optim_cfg = dict(type='Adam', lr=2e-4, betas=(0.9, 0.999))
optimizer = {
'generator':
obj_from_dict(optim_cfg, torch.optim,
dict(
params=getattr(restorer, 'generator').parameters())),
'discriminator':
obj_from_dict(
optim_cfg, torch.optim,
dict(params=getattr(restorer, 'discriminator').parameters()))
}
# no forward train in GAN models, raise ValueError
with pytest.raises(ValueError):
restorer(**data_batch, test_mode=False)
# test forward_test
with torch.no_grad():
outputs = restorer(**data_batch, test_mode=True)
assert torch.equal(outputs['lq'], data_batch['lq'])
assert torch.is_tensor(outputs['output'])
assert outputs['output'].size() == (1, 3, 128, 128)
# test forward_dummy
with torch.no_grad():
output = restorer.forward_dummy(data_batch['lq'])
assert torch.is_tensor(output)
assert output.size() == (1, 3, 128, 128)
# val_step
with torch.no_grad():
outputs = restorer.val_step(data_batch)
assert torch.equal(outputs['lq'], data_batch['lq'])
assert torch.is_tensor(outputs['output'])
assert outputs['output'].size() == (1, 3, 128, 128)
# test train_step
with patch.object(
restorer,
'perceptual_loss',
return_value=(torch.tensor(1.0), torch.tensor(2.0))):
outputs = restorer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
for v in [
'loss_perceptual', 'loss_gan', 'loss_d_real', 'loss_d_fake',
'loss_pix'
]:
assert isinstance(outputs['log_vars'][v], float)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['lq'], data_batch['lq'])
assert torch.equal(outputs['results']['gt'], data_batch['gt'])
assert torch.is_tensor(outputs['results']['output'])
assert outputs['results']['output'].size() == (1, 3, 128, 128)
# test train_step and forward_test (gpu)
if torch.cuda.is_available():
restorer = restorer.cuda()
optimizer = {
'generator':
obj_from_dict(
optim_cfg, torch.optim,
dict(params=getattr(restorer, 'generator').parameters())),
'discriminator':
obj_from_dict(
optim_cfg, torch.optim,
dict(params=getattr(restorer, 'discriminator').parameters()))
}
data_batch = {'lq': inputs.cuda(), 'gt': targets.cuda()}
# forward_test
with torch.no_grad():
outputs = restorer(**data_batch, test_mode=True)
assert torch.equal(outputs['lq'], data_batch['lq'].cpu())
assert torch.is_tensor(outputs['output'])
assert outputs['output'].size() == (1, 3, 128, 128)
# val_step
with torch.no_grad():
outputs = restorer.val_step(data_batch)
assert torch.equal(outputs['lq'], data_batch['lq'].cpu())
assert torch.is_tensor(outputs['output'])
assert outputs['output'].size() == (1, 3, 128, 128)
# train_step
with patch.object(
restorer,
'perceptual_loss',
return_value=(torch.tensor(1.0).cuda(),
torch.tensor(2.0).cuda())):
outputs = restorer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
for v in [
'loss_perceptual', 'loss_gan', 'loss_d_real',
'loss_d_fake', 'loss_pix'
]:
assert isinstance(outputs['log_vars'][v], float)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['lq'],
data_batch['lq'].cpu())
assert torch.equal(outputs['results']['gt'],
data_batch['gt'].cpu())
assert torch.is_tensor(outputs['results']['output'])
assert outputs['results']['output'].size() == (1, 3, 128, 128)
# test disc_steps and disc_init_steps
data_batch = {'lq': inputs.cpu(), 'gt': targets.cpu()}
train_cfg = dict(disc_steps=2, disc_init_steps=2)
restorer = build_model(model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
with patch.object(
restorer,
'perceptual_loss',
return_value=(torch.tensor(1.0), torch.tensor(2.0))):
outputs = restorer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
for v in ['loss_d_real', 'loss_d_fake']:
assert isinstance(outputs['log_vars'][v], float)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['lq'], data_batch['lq'])
assert torch.equal(outputs['results']['gt'], data_batch['gt'])
assert torch.is_tensor(outputs['results']['output'])
assert outputs['results']['output'].size() == (1, 3, 128, 128)
# test no discriminator (testing mode)
model_cfg_ = model_cfg.copy()
model_cfg_.pop('discriminator')
restorer = build_model(model_cfg_, train_cfg=train_cfg, test_cfg=test_cfg)
with torch.no_grad():
outputs = restorer(**data_batch, test_mode=True)
assert torch.equal(outputs['lq'], data_batch['lq'])
assert torch.is_tensor(outputs['output'])
assert outputs['output'].size() == (1, 3, 128, 128)
# test without pixel loss and perceptual loss
model_cfg_ = model_cfg.copy()
model_cfg_.pop('pixel_loss')
restorer = build_model(model_cfg_, train_cfg=None, test_cfg=None)
outputs = restorer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
for v in ['loss_gan', 'loss_d_real', 'loss_d_fake']:
assert isinstance(outputs['log_vars'][v], float)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['lq'], data_batch['lq'])
assert torch.equal(outputs['results']['gt'], data_batch['gt'])
assert torch.is_tensor(outputs['results']['output'])
assert outputs['results']['output'].size() == (1, 3, 128, 128)
# test train_step w/o loss_percep
restorer = build_model(model_cfg, train_cfg=None, test_cfg=None)
with patch.object(
restorer, 'perceptual_loss',
return_value=(None, torch.tensor(2.0))):
outputs = restorer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
for v in [
'loss_style', 'loss_gan', 'loss_d_real', 'loss_d_fake',
'loss_pix'
]:
assert isinstance(outputs['log_vars'][v], float)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['lq'], data_batch['lq'])
assert torch.equal(outputs['results']['gt'], data_batch['gt'])
assert torch.is_tensor(outputs['results']['output'])
assert outputs['results']['output'].size() == (1, 3, 128, 128)
# test train_step w/o loss_style
restorer = build_model(model_cfg, train_cfg=None, test_cfg=None)
with patch.object(
restorer, 'perceptual_loss',
return_value=(torch.tensor(2.0), None)):
outputs = restorer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
for v in [
'loss_perceptual', 'loss_gan', 'loss_d_real', 'loss_d_fake',
'loss_pix'
]:
assert isinstance(outputs['log_vars'][v], float)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['lq'], data_batch['lq'])
assert torch.equal(outputs['results']['gt'], data_batch['gt'])
assert torch.is_tensor(outputs['results']['output'])
assert outputs['results']['output'].size() == (1, 3, 128, 128)
| 9,665 | 39.107884 | 79 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_restorers/test_basic_restorer.py | # Copyright (c) OpenMMLab. All rights reserved.
import tempfile
import mmcv
import pytest
import torch
from mmcv.runner import obj_from_dict
from mmedit.models import build_model
from mmedit.models.backbones import MSRResNet
from mmedit.models.losses import L1Loss
def test_basic_restorer():
model_cfg = dict(
type='BasicRestorer',
generator=dict(
type='MSRResNet',
in_channels=3,
out_channels=3,
mid_channels=4,
num_blocks=1,
upscale_factor=4),
pixel_loss=dict(type='L1Loss', loss_weight=1.0, reduction='mean'))
train_cfg = None
test_cfg = None
# build restorer
restorer = build_model(model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
# test attributes
assert restorer.__class__.__name__ == 'BasicRestorer'
assert isinstance(restorer.generator, MSRResNet)
assert isinstance(restorer.pixel_loss, L1Loss)
# prepare data
inputs = torch.rand(1, 3, 20, 20)
targets = torch.rand(1, 3, 80, 80)
data_batch = {'lq': inputs, 'gt': targets}
# prepare optimizer
optim_cfg = dict(type='Adam', lr=2e-4, betas=(0.9, 0.999))
optimizer = {
'generator':
obj_from_dict(optim_cfg, torch.optim,
dict(params=restorer.parameters()))
}
# test forward train
outputs = restorer(**data_batch, test_mode=False)
assert isinstance(outputs, dict)
assert isinstance(outputs['losses'], dict)
assert isinstance(outputs['losses']['loss_pix'], torch.FloatTensor)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['lq'], data_batch['lq'])
assert torch.equal(outputs['results']['gt'], data_batch['gt'])
assert torch.is_tensor(outputs['results']['output'])
assert outputs['results']['output'].size() == (1, 3, 80, 80)
# test forward_test
with torch.no_grad():
outputs = restorer(**data_batch, test_mode=True)
assert torch.equal(outputs['lq'], data_batch['lq'])
assert torch.is_tensor(outputs['output'])
assert outputs['output'].size() == (1, 3, 80, 80)
# test forward_dummy
with torch.no_grad():
output = restorer.forward_dummy(data_batch['lq'])
assert torch.is_tensor(output)
assert output.size() == (1, 3, 80, 80)
# test train_step
outputs = restorer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
assert isinstance(outputs['log_vars']['loss_pix'], float)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['lq'], data_batch['lq'])
assert torch.equal(outputs['results']['gt'], data_batch['gt'])
assert torch.is_tensor(outputs['results']['output'])
assert outputs['results']['output'].size() == (1, 3, 80, 80)
# test train_step and forward_test (gpu)
if torch.cuda.is_available():
restorer = restorer.cuda()
optimizer['generator'] = obj_from_dict(
optim_cfg, torch.optim, dict(params=restorer.parameters()))
data_batch = {'lq': inputs.cuda(), 'gt': targets.cuda()}
# test forward train
outputs = restorer(**data_batch, test_mode=False)
assert isinstance(outputs, dict)
assert isinstance(outputs['losses'], dict)
assert isinstance(outputs['losses']['loss_pix'],
torch.cuda.FloatTensor)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['lq'], data_batch['lq'].cpu())
assert torch.equal(outputs['results']['gt'], data_batch['gt'].cpu())
assert torch.is_tensor(outputs['results']['output'])
assert outputs['results']['output'].size() == (1, 3, 80, 80)
# forward_test
with torch.no_grad():
outputs = restorer(**data_batch, test_mode=True)
assert torch.equal(outputs['lq'], data_batch['lq'].cpu())
assert torch.is_tensor(outputs['output'])
assert outputs['output'].size() == (1, 3, 80, 80)
# train_step
outputs = restorer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
assert isinstance(outputs['log_vars']['loss_pix'], float)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['lq'], data_batch['lq'].cpu())
assert torch.equal(outputs['results']['gt'], data_batch['gt'].cpu())
assert torch.is_tensor(outputs['results']['output'])
assert outputs['results']['output'].size() == (1, 3, 80, 80)
# test with metric and save image
test_cfg = dict(metrics=('PSNR', 'SSIM'), crop_border=0)
test_cfg = mmcv.Config(test_cfg)
data_batch = {
'lq': inputs,
'gt': targets,
'meta': [{
'lq_path': 'fake_path/fake_name.png'
}]
}
restorer = build_model(model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
with pytest.raises(AssertionError):
# evaluation with metrics must have gt images
restorer(lq=inputs, test_mode=True)
with tempfile.TemporaryDirectory() as tmpdir:
outputs = restorer(
**data_batch,
test_mode=True,
save_image=True,
save_path=tmpdir,
iteration=None)
assert isinstance(outputs, dict)
assert isinstance(outputs['eval_result'], dict)
assert isinstance(outputs['eval_result']['PSNR'], float)
assert isinstance(outputs['eval_result']['SSIM'], float)
outputs = restorer(
**data_batch,
test_mode=True,
save_image=True,
save_path=tmpdir,
iteration=100)
assert isinstance(outputs, dict)
assert isinstance(outputs['eval_result'], dict)
assert isinstance(outputs['eval_result']['PSNR'], float)
assert isinstance(outputs['eval_result']['SSIM'], float)
with pytest.raises(ValueError):
# iteration should be number or None
restorer(
**data_batch,
test_mode=True,
save_image=True,
save_path=tmpdir,
iteration='100')
| 6,226 | 35.415205 | 77 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_video_interpolator/test_basic_interpolator.py | # Copyright (c) OpenMMLab. All rights reserved.
import tempfile
import mmcv
import pytest
import torch
import torch.nn as nn
from mmcv.runner import obj_from_dict
from mmedit.models import build_model
from mmedit.models.losses import L1Loss
from mmedit.models.registry import COMPONENTS
@COMPONENTS.register_module()
class InterpolateExample(nn.Module):
"""An example of interpolate network for testing BasicInterpolator.
"""
def __init__(self):
super().__init__()
self.layer = nn.Conv2d(3, 3, 3, 1, 1)
def forward(self, x):
return self.layer(x[:, 0])
def init_weights(self, pretrained=None):
pass
@COMPONENTS.register_module()
class InterpolateExample2(nn.Module):
"""An example of interpolate network for testing BasicInterpolator.
"""
def __init__(self):
super().__init__()
self.layer = nn.Conv2d(3, 3, 3, 1, 1)
def forward(self, x):
return self.layer(x[:, 0]).unsqueeze(1)
def init_weights(self, pretrained=None):
pass
def test_basic_interpolator():
model_cfg = dict(
type='BasicInterpolator',
generator=dict(type='InterpolateExample'),
pixel_loss=dict(type='L1Loss', loss_weight=1.0, reduction='mean'))
train_cfg = None
test_cfg = None
# build restorer
restorer = build_model(model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
# test attributes
assert restorer.__class__.__name__ == 'BasicInterpolator'
assert isinstance(restorer.generator, InterpolateExample)
assert isinstance(restorer.pixel_loss, L1Loss)
# prepare data
inputs = torch.rand(1, 2, 3, 20, 20)
target = torch.rand(1, 3, 20, 20)
data_batch = {'inputs': inputs, 'target': target}
# prepare optimizer
optim_cfg = dict(type='Adam', lr=2e-4, betas=(0.9, 0.999))
optimizer = {
'generator':
obj_from_dict(optim_cfg, torch.optim,
dict(params=restorer.parameters()))
}
# test forward train
outputs = restorer(**data_batch, test_mode=False)
assert isinstance(outputs, dict)
assert isinstance(outputs['losses'], dict)
assert isinstance(outputs['losses']['loss_pix'], torch.FloatTensor)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['inputs'], data_batch['inputs'])
assert torch.equal(outputs['results']['target'], data_batch['target'])
assert torch.is_tensor(outputs['results']['output'])
assert outputs['results']['output'].size() == (1, 3, 20, 20)
# test forward_test
with torch.no_grad():
restorer.val_step(data_batch)
outputs = restorer(**data_batch, test_mode=True)
assert torch.equal(outputs['inputs'], data_batch['inputs'])
assert torch.is_tensor(outputs['output'])
assert outputs['output'].size() == (1, 3, 20, 20)
assert outputs['output'].max() <= 1.
assert outputs['output'].min() >= 0.
# test forward_dummy
with torch.no_grad():
output = restorer.forward_dummy(data_batch['inputs'])
assert torch.is_tensor(output)
assert output.size() == (1, 3, 20, 20)
# test train_step
outputs = restorer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
assert isinstance(outputs['log_vars']['loss_pix'], float)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['inputs'], data_batch['inputs'])
assert torch.equal(outputs['results']['target'], data_batch['target'])
assert torch.is_tensor(outputs['results']['output'])
assert outputs['results']['output'].size() == (1, 3, 20, 20)
# test train_step and forward_test (gpu)
if torch.cuda.is_available():
restorer = restorer.cuda()
optimizer['generator'] = obj_from_dict(
optim_cfg, torch.optim, dict(params=restorer.parameters()))
data_batch = {'inputs': inputs.cuda(), 'target': target.cuda()}
# test forward train
outputs = restorer(**data_batch, test_mode=False)
assert isinstance(outputs, dict)
assert isinstance(outputs['losses'], dict)
assert isinstance(outputs['losses']['loss_pix'],
torch.cuda.FloatTensor)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['inputs'],
data_batch['inputs'].cpu())
assert torch.equal(outputs['results']['target'],
data_batch['target'].cpu())
assert torch.is_tensor(outputs['results']['output'])
assert outputs['results']['output'].size() == (1, 3, 20, 20)
# forward_test
with torch.no_grad():
restorer.val_step(data_batch)
outputs = restorer(**data_batch, test_mode=True)
assert torch.equal(outputs['inputs'], data_batch['inputs'].cpu())
assert torch.is_tensor(outputs['output'])
assert outputs['output'].size() == (1, 3, 20, 20)
assert outputs['output'].max() <= 1.
assert outputs['output'].min() >= 0.
# train_step
outputs = restorer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
assert isinstance(outputs['log_vars']['loss_pix'], float)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['inputs'],
data_batch['inputs'].cpu())
assert torch.equal(outputs['results']['target'],
data_batch['target'].cpu())
assert torch.is_tensor(outputs['results']['output'])
assert outputs['results']['output'].size() == (1, 3, 20, 20)
# test with metric and save image
test_cfg = dict(metrics=('PSNR', 'SSIM'), crop_border=0)
test_cfg = mmcv.Config(test_cfg)
data_batch = {
'inputs': inputs,
'target': target,
'meta': [{
'key': '000001/0000',
'target_path': 'fake_path/fake_name.png'
}]
}
restorer = build_model(model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
with pytest.raises(AssertionError):
# evaluation with metrics must have target images
restorer(inputs=inputs, test_mode=True)
with tempfile.TemporaryDirectory() as tmpdir:
outputs = restorer(
**data_batch,
test_mode=True,
save_image=True,
save_path=tmpdir,
iteration=None)
assert isinstance(outputs, dict)
assert isinstance(outputs['eval_result'], dict)
assert isinstance(outputs['eval_result']['PSNR'], float)
assert isinstance(outputs['eval_result']['SSIM'], float)
outputs = restorer(
**data_batch,
test_mode=True,
save_image=True,
save_path=tmpdir,
iteration=100)
assert isinstance(outputs, dict)
assert isinstance(outputs['eval_result'], dict)
assert isinstance(outputs['eval_result']['PSNR'], float)
assert isinstance(outputs['eval_result']['SSIM'], float)
outputs = restorer(
inputs=inputs,
target=target,
meta=[{
'key':
'000001/0000',
'inputs_path':
['fake_path/fake_name.png', 'fake_path/fake_name.png']
}],
test_mode=True,
save_image=True,
save_path=tmpdir,
iteration=100)
assert isinstance(outputs, dict)
assert isinstance(outputs['eval_result'], dict)
assert isinstance(outputs['eval_result']['PSNR'], float)
assert isinstance(outputs['eval_result']['SSIM'], float)
with pytest.raises(ValueError):
# iteration should be number or None
restorer(
**data_batch,
test_mode=True,
save_image=True,
save_path=tmpdir,
iteration='100')
# test forward_test when output.shape==5
model_cfg = dict(
type='BasicInterpolator',
generator=dict(type='InterpolateExample2'),
pixel_loss=dict(type='L1Loss', loss_weight=1.0, reduction='mean'))
train_cfg = None
test_cfg = None
restorer = build_model(
model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
outputs = restorer(
inputs=inputs,
target=target.unsqueeze(1),
meta=[{
'key':
'000001/0000',
'inputs_path':
['fake_path/fake_name.png', 'fake_path/fake_name.png']
}],
test_mode=True,
save_image=True,
save_path=tmpdir,
iteration=100)
outputs = restorer(
inputs=inputs,
target=target.unsqueeze(1),
meta=[{
'key':
'000001/0000',
'inputs_path':
['fake_path/fake_name.png', 'fake_path/fake_name.png']
}],
test_mode=True,
save_image=True,
save_path=tmpdir,
iteration=None)
with pytest.raises(ValueError):
# iteration should be number or None
restorer(
**data_batch,
test_mode=True,
save_image=True,
save_path=tmpdir,
iteration='100')
# test merge_frames
input_tensors = torch.rand(2, 2, 3, 256, 256)
output_tensors = torch.rand(2, 1, 3, 256, 256)
result = restorer.merge_frames(input_tensors, output_tensors)
assert isinstance(result, list)
assert len(result) == 5
assert result[0].shape == (256, 256, 3)
# test split_frames
tensors = torch.rand(1, 10, 3, 256, 256)
result = restorer.split_frames(tensors)
assert isinstance(result, torch.Tensor)
assert result.shape == (9, 2, 3, 256, 256)
# test evaluate 5d output
test_cfg = dict(metrics=('PSNR', 'SSIM'), crop_border=0)
test_cfg = mmcv.Config(test_cfg)
restorer = build_model(model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
output = torch.rand(1, 2, 3, 256, 256)
target = torch.rand(1, 2, 3, 256, 256)
restorer.evaluate(output, target)
| 10,311 | 34.07483 | 78 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_video_interpolator/test_cain.py | # Copyright (c) OpenMMLab. All rights reserved.
import tempfile
import mmcv
import pytest
import torch
from mmcv.runner import obj_from_dict
from mmedit.models import build_model
from mmedit.models.backbones import CAINNet
from mmedit.models.losses import L1Loss
def test_cain():
model_cfg = dict(
type='CAIN',
generator=dict(type='CAINNet'),
pixel_loss=dict(type='L1Loss', loss_weight=1.0, reduction='mean'))
train_cfg = None
test_cfg = None
# build restorer
restorer = build_model(model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
# test attributes
assert restorer.__class__.__name__ == 'CAIN'
assert isinstance(restorer.generator, CAINNet)
assert isinstance(restorer.pixel_loss, L1Loss)
# prepare data
inputs = torch.rand(1, 2, 3, 128, 128)
target = torch.rand(1, 3, 128, 128)
data_batch = {'inputs': inputs, 'target': target, 'meta': [{'key': '001'}]}
# prepare optimizer
optim_cfg = dict(type='Adam', lr=2e-4, betas=(0.9, 0.999))
optimizer = {
'generator':
obj_from_dict(optim_cfg, torch.optim,
dict(params=restorer.parameters()))
}
# test forward_test
with torch.no_grad():
outputs = restorer.forward_test(**data_batch)
assert torch.equal(outputs['inputs'], data_batch['inputs'])
assert torch.is_tensor(outputs['output'])
assert outputs['output'].size() == (1, 3, 128, 128)
# test train_step
outputs = restorer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
assert isinstance(outputs['log_vars']['loss_pix'], float)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['inputs'], data_batch['inputs'])
assert torch.equal(outputs['results']['target'], data_batch['target'])
assert torch.is_tensor(outputs['results']['output'])
assert outputs['results']['output'].size() == (1, 3, 128, 128)
# test train_step and forward_test (gpu)
if torch.cuda.is_available():
restorer = restorer.cuda()
optimizer['generator'] = obj_from_dict(
optim_cfg, torch.optim, dict(params=restorer.parameters()))
data_batch = {
'inputs': inputs.cuda(),
'target': target.cuda(),
'meta': [{
'key': '001'
}]
}
# forward_test
with torch.no_grad():
outputs = restorer.forward_test(**data_batch)
assert torch.equal(outputs['inputs'], data_batch['inputs'].cpu())
assert torch.is_tensor(outputs['output'])
assert outputs['output'].size() == (1, 3, 128, 128)
# train_step
outputs = restorer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
assert isinstance(outputs['log_vars']['loss_pix'], float)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['inputs'],
data_batch['inputs'].cpu())
assert torch.equal(outputs['results']['target'],
data_batch['target'].cpu())
assert torch.is_tensor(outputs['results']['output'])
assert outputs['results']['output'].size() == (1, 3, 128, 128)
# test with metric and save image
test_cfg = dict(metrics=('PSNR', 'SSIM'), crop_border=0)
test_cfg = mmcv.Config(test_cfg)
data_batch = {
'inputs': inputs,
'target': target,
'meta': [{
'key': 'fake_path/fake_name'
}]
}
restorer = build_model(model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
with pytest.raises(AssertionError):
# evaluation with metrics must have target images
restorer(inputs=inputs, test_mode=True)
with tempfile.TemporaryDirectory() as tmpdir:
outputs = restorer(
**data_batch,
test_mode=True,
save_image=True,
save_path=tmpdir,
iteration=None)
assert isinstance(outputs, dict)
assert isinstance(outputs['eval_result'], dict)
assert isinstance(outputs['eval_result']['PSNR'], float)
assert isinstance(outputs['eval_result']['SSIM'], float)
outputs = restorer(
**data_batch,
test_mode=True,
save_image=True,
save_path=tmpdir,
iteration=100)
assert isinstance(outputs, dict)
assert isinstance(outputs['eval_result'], dict)
assert isinstance(outputs['eval_result']['PSNR'], float)
assert isinstance(outputs['eval_result']['SSIM'], float)
| 4,692 | 33.762963 | 79 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_mattors/test_mattors.py | # Copyright (c) OpenMMLab. All rights reserved.
import os.path as osp
from unittest.mock import patch
import mmcv
import numpy as np
import pytest
import torch
from mmedit.models import BaseMattor, build_model
def _get_model_cfg(fname):
"""
Grab configs necessary to create a model. These are deep copied to allow
for safe modification of parameters without influencing other tests.
"""
config_dpath = 'configs/mattors'
config_fpath = osp.join(config_dpath, fname)
if not osp.exists(config_dpath):
raise Exception('Cannot find config path')
config = mmcv.Config.fromfile(config_fpath)
return config.model, config.train_cfg, config.test_cfg
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)
@patch.multiple(BaseMattor, __abstractmethods__=set())
def test_base_mattor():
backbone = dict(
type='SimpleEncoderDecoder',
encoder=dict(type='VGG16', in_channels=4),
decoder=dict(type='PlainDecoder'))
refiner = dict(type='PlainRefiner')
train_cfg = mmcv.ConfigDict(train_backbone=True, train_refiner=True)
test_cfg = mmcv.ConfigDict(
refine=True, metrics=['SAD', 'MSE', 'GRAD', 'CONN'])
with pytest.raises(KeyError):
# metrics should be specified in test_cfg
BaseMattor(
backbone,
refiner,
train_cfg.copy(),
test_cfg=mmcv.ConfigDict(refine=True))
with pytest.raises(KeyError):
# supported metric should be one of {'SAD', 'MSE'}
BaseMattor(
backbone,
refiner,
train_cfg.copy(),
test_cfg=mmcv.ConfigDict(
refine=True, metrics=['UnsupportedMetric']))
with pytest.raises(TypeError):
# metrics must be None or a list of str
BaseMattor(
backbone,
refiner,
train_cfg.copy(),
test_cfg=mmcv.ConfigDict(refine=True, metrics='SAD'))
# build mattor without refiner
mattor = BaseMattor(
backbone, refiner=None, train_cfg=None, test_cfg=test_cfg.copy())
assert not mattor.with_refiner
# only train the refiner, this will freeze the backbone
mattor = BaseMattor(
backbone,
refiner,
train_cfg=mmcv.ConfigDict(train_backbone=False, train_refiner=True),
test_cfg=test_cfg.copy())
assert not mattor.train_cfg.train_backbone
assert mattor.train_cfg.train_refiner
assert mattor.test_cfg.refine
# only train the backbone while the refiner is used for inference but not
# trained, this behavior is allowed currently but will cause a warning.
mattor = BaseMattor(
backbone,
refiner,
train_cfg=mmcv.ConfigDict(train_backbone=True, train_refiner=False),
test_cfg=test_cfg.copy())
assert mattor.train_cfg.train_backbone
assert not mattor.train_cfg.train_refiner
assert mattor.test_cfg.refine
def test_dim():
model_cfg, train_cfg, test_cfg = _get_model_cfg(
'dim/dim_stage3_v16_pln_1x1_1000k_comp1k.py')
model_cfg['pretrained'] = None
# 1. test dim model with refiner
train_cfg.train_refiner = True
test_cfg.refine = True
# test model forward in train mode
model = build_model(model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
input_train = _demo_input_train((64, 64))
output_train = model(**input_train)
assert output_train['num_samples'] == 1
assert_dict_keys_equal(output_train['losses'],
['loss_alpha', 'loss_comp', 'loss_refine'])
# test model forward in train mode with gpu
if torch.cuda.is_available():
model = build_model(model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
model.cuda()
input_train = _demo_input_train((64, 64), cuda=True)
output_train = model(**input_train)
assert output_train['num_samples'] == 1
assert_dict_keys_equal(output_train['losses'],
['loss_alpha', 'loss_comp', 'loss_refine'])
# test model forward in test mode
with torch.no_grad():
model = build_model(model_cfg, train_cfg=None, test_cfg=test_cfg)
input_test = _demo_input_test((64, 64))
output_test = model(**input_test, test_mode=True)
assert isinstance(output_test['pred_alpha'], np.ndarray)
assert_dict_keys_equal(output_test['eval_result'],
['SAD', 'MSE', 'GRAD', 'CONN'])
# test model forward in test mode with gpu
if torch.cuda.is_available():
model = build_model(model_cfg, train_cfg=None, test_cfg=test_cfg)
model.cuda()
input_test = _demo_input_test((64, 64), cuda=True)
output_test = model(**input_test, test_mode=True)
assert isinstance(output_test['pred_alpha'], np.ndarray)
assert_dict_keys_equal(output_test['eval_result'],
['SAD', 'MSE', 'GRAD', 'CONN'])
# 2. test dim model without refiner
model_cfg['refiner'] = None
test_cfg['metrics'] = None
# test model forward in train mode
model = build_model(model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
input_train = _demo_input_train((64, 64))
output_train = model(**input_train)
assert output_train['num_samples'] == 1
assert_dict_keys_equal(output_train['losses'], ['loss_alpha', 'loss_comp'])
# test model forward in train mode with gpu
if torch.cuda.is_available():
model = build_model(model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
model.cuda()
input_train = _demo_input_train((64, 64), cuda=True)
output_train = model(**input_train)
assert output_train['num_samples'] == 1
assert_dict_keys_equal(output_train['losses'],
['loss_alpha', 'loss_comp'])
# test model forward in test mode
with torch.no_grad():
model = build_model(model_cfg, train_cfg=None, test_cfg=test_cfg)
input_test = _demo_input_test((64, 64))
output_test = model(**input_test, test_mode=True)
assert isinstance(output_test['pred_alpha'], np.ndarray)
assert output_test['eval_result'] is None
# check test with gpu
if torch.cuda.is_available():
model = build_model(model_cfg, train_cfg=None, test_cfg=test_cfg)
model.cuda()
input_test = _demo_input_test((64, 64), cuda=True)
output_test = model(**input_test, test_mode=True)
assert isinstance(output_test['pred_alpha'], np.ndarray)
assert output_test['eval_result'] is None
# test forward_dummy
model.cpu().eval()
inputs = torch.ones((1, 4, 32, 32))
model.forward_dummy(inputs)
def test_indexnet():
model_cfg, _, test_cfg = _get_model_cfg(
'indexnet/indexnet_mobv2_1x16_78k_comp1k.py')
model_cfg['pretrained'] = None
# test indexnet inference
with torch.no_grad():
indexnet = build_model(model_cfg, train_cfg=None, test_cfg=test_cfg)
indexnet.eval()
input_test = _demo_input_test((64, 64))
output_test = indexnet(**input_test, test_mode=True)
assert isinstance(output_test['pred_alpha'], np.ndarray)
assert output_test['pred_alpha'].shape == (64, 64)
assert_dict_keys_equal(output_test['eval_result'],
['SAD', 'MSE', 'GRAD', 'CONN'])
# test inference with gpu
if torch.cuda.is_available():
indexnet = build_model(
model_cfg, train_cfg=None, test_cfg=test_cfg).cuda()
indexnet.eval()
input_test = _demo_input_test((64, 64), cuda=True)
output_test = indexnet(**input_test, test_mode=True)
assert isinstance(output_test['pred_alpha'], np.ndarray)
assert output_test['pred_alpha'].shape == (64, 64)
assert_dict_keys_equal(output_test['eval_result'],
['SAD', 'MSE', 'GRAD', 'CONN'])
# test forward train though we do not guarantee the training for present
model_cfg.loss_alpha = None
model_cfg.loss_comp = dict(type='L1CompositionLoss')
indexnet = build_model(
model_cfg,
train_cfg=mmcv.ConfigDict(train_backbone=True),
test_cfg=test_cfg)
input_train = _demo_input_train((64, 64), batch_size=2)
output_train = indexnet(**input_train)
assert output_train['num_samples'] == 2
assert_dict_keys_equal(output_train['losses'], ['loss_comp'])
if torch.cuda.is_available():
model_cfg.loss_alpha = dict(type='L1Loss')
model_cfg.loss_comp = None
indexnet = build_model(
model_cfg,
train_cfg=mmcv.ConfigDict(train_backbone=True),
test_cfg=test_cfg).cuda()
input_train = _demo_input_train((64, 64), batch_size=2, cuda=True)
output_train = indexnet(**input_train)
assert output_train['num_samples'] == 2
assert_dict_keys_equal(output_train['losses'], ['loss_alpha'])
# test forward_dummy
indexnet.cpu().eval()
inputs = torch.ones((1, 4, 32, 32))
indexnet.forward_dummy(inputs)
def test_gca():
model_cfg, train_cfg, test_cfg = _get_model_cfg(
'gca/gca_r34_4x10_200k_comp1k.py')
model_cfg['pretrained'] = None
# test model forward in train mode
model = build_model(model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
inputs = _demo_input_train((64, 64), batch_size=2)
inputs['trimap'] = inputs['trimap'].expand_as(inputs['merged'])
inputs['meta'][0]['to_onehot'] = True
outputs = model(inputs['merged'], inputs['trimap'], inputs['meta'],
inputs['alpha'])
assert outputs['num_samples'] == 2
assert_dict_keys_equal(outputs['losses'], ['loss'])
if torch.cuda.is_available():
model = build_model(model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
model.cuda()
inputs = _demo_input_train((64, 64), batch_size=2, cuda=True)
inputs['trimap'] = inputs['trimap'].expand_as(inputs['merged'])
inputs['meta'][0]['to_onehot'] = True
outputs = model(inputs['merged'], inputs['trimap'], inputs['meta'],
inputs['alpha'])
assert outputs['num_samples'] == 2
assert_dict_keys_equal(outputs['losses'], ['loss'])
# test model forward in test mode
with torch.no_grad():
model_cfg.backbone.encoder.in_channels = 4
model = build_model(model_cfg, train_cfg=None, test_cfg=test_cfg)
inputs = _demo_input_test((64, 64))
outputs = model(**inputs, test_mode=True)
assert_dict_keys_equal(outputs['eval_result'],
['SAD', 'MSE', 'GRAD', 'CONN'])
if torch.cuda.is_available():
model = build_model(model_cfg, train_cfg=None, test_cfg=test_cfg)
model.cuda()
inputs = _demo_input_test((64, 64), cuda=True)
outputs = model(**inputs, test_mode=True)
assert_dict_keys_equal(outputs['eval_result'],
['SAD', 'MSE', 'GRAD', 'CONN'])
# test forward_dummy
model.cpu().eval()
inputs = torch.ones((1, 4, 32, 32))
model.forward_dummy(inputs)
def _demo_input_train(img_shape, batch_size=1, cuda=False):
"""
Create a superset of inputs needed to run backbone.
Args:
img_shape (tuple): shape of the input image.
batch_size (int): batch size of the input batch.
cuda (bool): whether transfer input into gpu.
"""
color_shape = (batch_size, 3, img_shape[0], img_shape[1])
gray_shape = (batch_size, 1, img_shape[0], img_shape[1])
merged = torch.from_numpy(np.random.random(color_shape).astype(np.float32))
trimap = torch.from_numpy(
np.random.randint(255, size=gray_shape).astype(np.float32))
meta = [{}] * batch_size
alpha = torch.from_numpy(np.random.random(gray_shape).astype(np.float32))
ori_merged = torch.from_numpy(
np.random.random(color_shape).astype(np.float32))
fg = torch.from_numpy(np.random.random(color_shape).astype(np.float32))
bg = torch.from_numpy(np.random.random(color_shape).astype(np.float32))
if cuda:
merged = merged.cuda()
trimap = trimap.cuda()
alpha = alpha.cuda()
ori_merged = ori_merged.cuda()
fg = fg.cuda()
bg = bg.cuda()
return dict(
merged=merged,
trimap=trimap,
meta=meta,
alpha=alpha,
ori_merged=ori_merged,
fg=fg,
bg=bg)
def _demo_input_test(img_shape, batch_size=1, cuda=False, test_trans='resize'):
"""
Create a superset of inputs needed to run backbone.
Args:
img_shape (tuple): shape of the input image.
batch_size (int): batch size of the input batch.
cuda (bool): whether transfer input into gpu.
test_trans (str): what test transformation is used in data pipeline.
"""
color_shape = (batch_size, 3, img_shape[0], img_shape[1])
gray_shape = (batch_size, 1, img_shape[0], img_shape[1])
merged = torch.from_numpy(np.random.random(color_shape).astype(np.float32))
trimap = torch.from_numpy(
np.random.randint(255, size=gray_shape).astype(np.float32))
ori_alpha = np.random.random(img_shape).astype(np.float32)
ori_trimap = np.random.randint(256, size=img_shape).astype(np.float32)
if cuda:
merged = merged.cuda()
trimap = trimap.cuda()
meta = [
dict(
ori_alpha=ori_alpha,
ori_trimap=ori_trimap,
merged_ori_shape=img_shape)
] * batch_size
if test_trans == 'pad':
meta[0]['pad'] = (0, 0)
elif test_trans == 'resize':
# we just test bilinear as the interpolation method
meta[0]['interpolation'] = 'bilinear'
return dict(merged=merged, trimap=trimap, meta=meta)
| 14,057 | 37.620879 | 79 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_losses/test_losses.py | # Copyright (c) OpenMMLab. All rights reserved.
import math
from unittest.mock import patch
import numpy
import numpy.testing as npt
import pytest
import torch
from mmedit.models import (CharbonnierCompLoss, CharbonnierLoss, DiscShiftLoss,
GANLoss, GaussianBlur, GradientLoss,
GradientPenaltyLoss, L1CompositionLoss, L1Loss,
MaskedTVLoss, MSECompositionLoss, MSELoss,
PerceptualLoss, PerceptualVGG,
TransferalPerceptualLoss, mask_reduce_loss,
reduce_loss)
def test_utils():
loss = torch.rand(1, 3, 4, 4)
weight = torch.zeros(1, 3, 4, 4)
weight[:, :, :2, :2] = 1
# test reduce_loss()
reduced = reduce_loss(loss, 'none')
assert reduced is loss
reduced = reduce_loss(loss, 'mean')
npt.assert_almost_equal(reduced.numpy(), loss.mean())
reduced = reduce_loss(loss, 'sum')
npt.assert_almost_equal(reduced.numpy(), loss.sum())
# test mask_reduce_loss()
reduced = mask_reduce_loss(loss, weight=None, reduction='none')
assert reduced is loss
reduced = mask_reduce_loss(loss, weight=weight, reduction='mean')
target = (loss *
weight).sum(dim=[1, 2, 3]) / weight.sum(dim=[1, 2, 3]).mean()
npt.assert_almost_equal(reduced.numpy(), target)
reduced = mask_reduce_loss(loss, weight=weight, reduction='sum')
npt.assert_almost_equal(reduced.numpy(), (loss * weight).sum())
weight_single_channel = weight[:, 0:1, ...]
reduced = mask_reduce_loss(
loss, weight=weight_single_channel, reduction='mean')
target = (loss *
weight).sum(dim=[1, 2, 3]) / weight.sum(dim=[1, 2, 3]).mean()
npt.assert_almost_equal(reduced.numpy(), target)
loss_b = torch.rand(2, 3, 4, 4)
weight_b = torch.zeros(2, 1, 4, 4)
weight_b[0, :, :3, :3] = 1
weight_b[1, :, :2, :2] = 1
reduced = mask_reduce_loss(loss_b, weight=weight_b, reduction='mean')
target = (loss_b * weight_b).sum() / weight_b.sum() / 3.
npt.assert_almost_equal(reduced.numpy(), target)
with pytest.raises(AssertionError):
weight_wrong = weight[0, 0, ...]
reduced = mask_reduce_loss(loss, weight=weight_wrong, reduction='mean')
with pytest.raises(AssertionError):
weight_wrong = weight[:, 0:2, ...]
reduced = mask_reduce_loss(loss, weight=weight_wrong, reduction='mean')
def test_pixelwise_losses():
with pytest.raises(ValueError):
# only 'none', 'mean' and 'sum' are supported
L1Loss(reduction='InvalidValue')
with pytest.raises(ValueError):
# only 'none', 'mean' and 'sum' are supported
MSELoss(reduction='InvalidValue')
with pytest.raises(ValueError):
# only 'none', 'mean' and 'sum' are supported
CharbonnierLoss(reduction='InvalidValue')
unknown_h, unknown_w = (32, 32)
weight = torch.zeros(1, 1, 64, 64)
weight[0, 0, :unknown_h, :unknown_w] = 1
pred = weight.clone()
target = weight.clone() * 2
# test l1 loss
l1_loss = L1Loss(loss_weight=1.0, reduction='mean')
loss = l1_loss(pred, target)
assert loss.shape == ()
assert loss.item() == 0.25
l1_loss = L1Loss(loss_weight=0.5, reduction='none')
loss = l1_loss(pred, target, weight)
assert loss.shape == (1, 1, 64, 64)
assert (loss == torch.ones(1, 1, 64, 64) * weight * 0.5).all()
l1_loss = L1Loss(loss_weight=0.5, reduction='sum')
loss = l1_loss(pred, target, weight)
assert loss.shape == ()
assert loss.item() == 512
# test mse loss
mse_loss = MSELoss(loss_weight=1.0, reduction='mean')
loss = mse_loss(pred, target)
assert loss.shape == ()
assert loss.item() == 0.25
mse_loss = MSELoss(loss_weight=0.5, reduction='none')
loss = mse_loss(pred, target, weight)
assert loss.shape == (1, 1, 64, 64)
assert (loss == torch.ones(1, 1, 64, 64) * weight * 0.5).all()
mse_loss = MSELoss(loss_weight=0.5, reduction='sum')
loss = mse_loss(pred, target, weight)
assert loss.shape == ()
assert loss.item() == 512
# test charbonnier loss
charbonnier_loss = CharbonnierLoss(
loss_weight=1.0, reduction='mean', eps=1e-12)
loss = charbonnier_loss(pred, target)
assert loss.shape == ()
assert math.isclose(loss.item(), 0.25, rel_tol=1e-5)
charbonnier_loss = CharbonnierLoss(
loss_weight=0.5, reduction='none', eps=1e-6)
loss = charbonnier_loss(pred, target, weight)
assert loss.shape == (1, 1, 64, 64)
npt.assert_almost_equal(
loss.numpy(), torch.ones(1, 1, 64, 64) * weight * 0.5, decimal=6)
charbonnier_loss = CharbonnierLoss(
loss_weight=0.5, reduction='sum', eps=1e-12)
loss = charbonnier_loss(pred, target)
assert loss.shape == ()
assert math.isclose(loss.item(), 512, rel_tol=1e-5)
# test samplewise option, use L1Loss as an example
unknown_h, unknown_w = (32, 32)
weight = torch.zeros(2, 1, 64, 64)
weight[0, 0, :unknown_h, :unknown_w] = 1
# weight[1, 0, :unknown_h // 2, :unknown_w // 2] = 1
pred = weight.clone()
target = weight.clone()
# make mean l1_loss of sample 2 different from sample 1
target[0, ...] *= 2
l1_loss = L1Loss(loss_weight=1.0, reduction='mean', sample_wise=True)
loss = l1_loss(pred, target, weight)
assert loss.shape == ()
assert loss.item() == 0.5
masked_tv_loss = MaskedTVLoss(loss_weight=1.0)
pred = torch.zeros((1, 1, 6, 6))
mask = torch.zeros_like(pred)
mask[..., 2:4, 2:4] = 1.
pred[..., 3, :] = 1.
loss = masked_tv_loss(pred, mask)
assert loss.shape == ()
npt.assert_almost_equal(loss.item(), 1.)
def test_composition_losses():
with pytest.raises(ValueError):
# only 'none', 'mean' and 'sum' are supported
L1CompositionLoss(reduction='InvalidValue')
with pytest.raises(ValueError):
# only 'none', 'mean' and 'sum' are supported
MSECompositionLoss(reduction='InvalidValue')
with pytest.raises(ValueError):
# only 'none', 'mean' and 'sum' are supported
CharbonnierCompLoss(reduction='InvalidValue')
unknown_h, unknown_w = (32, 32)
weight = torch.zeros(1, 1, 64, 64)
weight[0, 0, :unknown_h, :unknown_w] = 1
pred_alpha = weight.clone() * 0.5
ori_merged = torch.ones(1, 3, 64, 64)
fg = torch.zeros(1, 3, 64, 64)
bg = torch.ones(1, 3, 64, 64) * 4
l1_comp_loss = L1CompositionLoss(loss_weight=1.0, reduction='mean')
loss = l1_comp_loss(pred_alpha, fg, bg, ori_merged)
assert loss.shape == ()
assert loss.item() == 2.5
l1_comp_loss = L1CompositionLoss(loss_weight=0.5, reduction='none')
loss = l1_comp_loss(pred_alpha, fg, bg, ori_merged, weight)
assert loss.shape == (1, 3, 64, 64)
assert (loss == torch.ones(1, 3, 64, 64) * weight * 0.5).all()
l1_comp_loss = L1CompositionLoss(loss_weight=0.5, reduction='sum')
loss = l1_comp_loss(pred_alpha, fg, bg, ori_merged, weight)
assert loss.shape == ()
assert loss.item() == 1536
mse_comp_loss = MSECompositionLoss(loss_weight=1.0, reduction='mean')
loss = mse_comp_loss(pred_alpha, fg, bg, ori_merged)
assert loss.shape == ()
assert loss.item() == 7.0
mse_comp_loss = MSECompositionLoss(loss_weight=0.5, reduction='none')
loss = mse_comp_loss(pred_alpha, fg, bg, ori_merged, weight)
assert loss.shape == (1, 3, 64, 64)
assert (loss == torch.ones(1, 3, 64, 64) * weight * 0.5).all()
mse_comp_loss = MSECompositionLoss(loss_weight=0.5, reduction='sum')
loss = mse_comp_loss(pred_alpha, fg, bg, ori_merged, weight)
assert loss.shape == ()
assert loss.item() == 1536
cb_comp_loss = CharbonnierCompLoss(
loss_weight=1.0, reduction='mean', eps=1e-12)
loss = cb_comp_loss(pred_alpha, fg, bg, ori_merged)
assert loss.shape == ()
assert loss.item() == 2.5
cb_comp_loss = CharbonnierCompLoss(
loss_weight=0.5, reduction='none', eps=1e-6)
loss = cb_comp_loss(pred_alpha, fg, bg, ori_merged, weight)
assert loss.shape == (1, 3, 64, 64)
npt.assert_almost_equal(
loss.numpy(), torch.ones(1, 3, 64, 64) * weight * 0.5, decimal=6)
cb_comp_loss = CharbonnierCompLoss(
loss_weight=0.5, reduction='sum', eps=1e-6)
loss = cb_comp_loss(pred_alpha, fg, bg, ori_merged, weight)
assert loss.shape == ()
assert math.isclose(loss.item(), 1536, rel_tol=1e-6)
@patch.object(PerceptualVGG, 'init_weights')
def test_perceptual_loss(init_weights):
if torch.cuda.is_available():
loss_percep = PerceptualLoss(layer_weights={'0': 1.}).cuda()
x = torch.randn(1, 3, 16, 16).cuda()
x.requires_grad = True
gt = torch.randn(1, 3, 16, 16).cuda()
percep, style = loss_percep(x, gt)
assert percep.item() > 0
assert style.item() > 0
optim = torch.optim.SGD(params=[x], lr=10)
optim.zero_grad()
percep.backward()
optim.step()
percep_new, _ = loss_percep(x, gt)
assert percep_new < percep
loss_percep = PerceptualLoss(
layer_weights={
'0': 1.
}, perceptual_weight=0.).cuda()
x = torch.randn(1, 3, 16, 16).cuda()
gt = torch.randn(1, 3, 16, 16).cuda()
percep, style = loss_percep(x, gt)
assert percep is None and style > 0
loss_percep = PerceptualLoss(
layer_weights={
'0': 1.
}, style_weight=0., criterion='mse').cuda()
x = torch.randn(1, 3, 16, 16).cuda()
gt = torch.randn(1, 3, 16, 16).cuda()
percep, style = loss_percep(x, gt)
assert style is None and percep > 0
loss_percep = PerceptualLoss(
layer_weights={
'0': 1.
}, layer_weights_style={
'1': 1.
}).cuda()
x = torch.randn(1, 3, 16, 16).cuda()
gt = torch.randn(1, 3, 16, 16).cuda()
percep, style = loss_percep(x, gt)
assert percep > 0 and style > 0
# test whether vgg type is valid
with pytest.raises(AssertionError):
loss_percep = PerceptualLoss(layer_weights={'0': 1.}, vgg_type='igccc')
# test whether criterion is valid
with pytest.raises(NotImplementedError):
loss_percep = PerceptualLoss(
layer_weights={'0': 1.}, criterion='igccc')
layer_name_list = ['2', '10', '30']
vgg_model = PerceptualVGG(
layer_name_list,
use_input_norm=False,
vgg_type='vgg16',
pretrained='torchvision://vgg16')
x = torch.rand((1, 3, 32, 32))
output = vgg_model(x)
assert isinstance(output, dict)
assert len(output) == len(layer_name_list)
assert set(output.keys()) == set(layer_name_list)
# test whether the layer name is valid
with pytest.raises(AssertionError):
layer_name_list = ['2', '10', '30', '100']
vgg_model = PerceptualVGG(
layer_name_list,
use_input_norm=False,
vgg_type='vgg16',
pretrained='torchvision://vgg16')
# reset mock to clear some memory usage
init_weights.reset_mock()
def test_t_perceptual_loss():
maps = [
torch.rand((2, 8, 8, 8), requires_grad=True),
torch.rand((2, 4, 16, 16), requires_grad=True)
]
textures = [torch.rand((2, 8, 8, 8)), torch.rand((2, 4, 16, 16))]
soft = torch.rand((2, 1, 8, 8))
loss_t_percep = TransferalPerceptualLoss()
t_percep = loss_t_percep(maps, soft, textures)
assert t_percep.item() > 0
loss_t_percep = TransferalPerceptualLoss(
use_attention=False, criterion='l1')
t_percep = loss_t_percep(maps, soft, textures)
assert t_percep.item() > 0
if torch.cuda.is_available():
maps = [
torch.rand((2, 8, 8, 8)).cuda(),
torch.rand((2, 4, 16, 16)).cuda()
]
textures = [
torch.rand((2, 8, 8, 8)).cuda(),
torch.rand((2, 4, 16, 16)).cuda()
]
soft = torch.rand((2, 1, 8, 8)).cuda()
loss_t_percep = TransferalPerceptualLoss().cuda()
maps[0].requires_grad = True
maps[1].requires_grad = True
t_percep = loss_t_percep(maps, soft, textures)
assert t_percep.item() > 0
optim = torch.optim.SGD(params=maps, lr=10)
optim.zero_grad()
t_percep.backward()
optim.step()
t_percep_new = loss_t_percep(maps, soft, textures)
assert t_percep_new < t_percep
loss_t_percep = TransferalPerceptualLoss(
use_attention=False, criterion='l1').cuda()
t_percep = loss_t_percep(maps, soft, textures)
assert t_percep.item() > 0
# test whether vgg type is valid
with pytest.raises(ValueError):
TransferalPerceptualLoss(criterion='l2')
def test_gan_losses():
"""Test gan losses."""
with pytest.raises(NotImplementedError):
GANLoss(
'xixihaha',
loss_weight=1.0,
real_label_val=1.0,
fake_label_val=0.0)
input_1 = torch.ones(1, 1)
input_2 = torch.ones(1, 3, 6, 6) * 2
# vanilla
gan_loss = GANLoss(
'vanilla', loss_weight=2.0, real_label_val=1.0, fake_label_val=0.0)
loss = gan_loss(input_1, True, is_disc=False)
npt.assert_almost_equal(loss.item(), 0.6265233)
loss = gan_loss(input_1, False, is_disc=False)
npt.assert_almost_equal(loss.item(), 2.6265232)
loss = gan_loss(input_1, True, is_disc=True)
npt.assert_almost_equal(loss.item(), 0.3132616)
loss = gan_loss(input_1, False, is_disc=True)
npt.assert_almost_equal(loss.item(), 1.3132616)
# lsgan
gan_loss = GANLoss(
'lsgan', loss_weight=2.0, real_label_val=1.0, fake_label_val=0.0)
loss = gan_loss(input_2, True, is_disc=False)
npt.assert_almost_equal(loss.item(), 2.0)
loss = gan_loss(input_2, False, is_disc=False)
npt.assert_almost_equal(loss.item(), 8.0)
loss = gan_loss(input_2, True, is_disc=True)
npt.assert_almost_equal(loss.item(), 1.0)
loss = gan_loss(input_2, False, is_disc=True)
npt.assert_almost_equal(loss.item(), 4.0)
# wgan
gan_loss = GANLoss(
'wgan', loss_weight=2.0, real_label_val=1.0, fake_label_val=0.0)
loss = gan_loss(input_2, True, is_disc=False)
npt.assert_almost_equal(loss.item(), -4.0)
loss = gan_loss(input_2, False, is_disc=False)
npt.assert_almost_equal(loss.item(), 4)
loss = gan_loss(input_2, True, is_disc=True)
npt.assert_almost_equal(loss.item(), -2.0)
loss = gan_loss(input_2, False, is_disc=True)
npt.assert_almost_equal(loss.item(), 2.0)
# hinge
gan_loss = GANLoss(
'hinge', loss_weight=2.0, real_label_val=1.0, fake_label_val=0.0)
loss = gan_loss(input_2, True, is_disc=False)
npt.assert_almost_equal(loss.item(), -4.0)
loss = gan_loss(input_2, False, is_disc=False)
npt.assert_almost_equal(loss.item(), -4.0)
loss = gan_loss(input_2, True, is_disc=True)
npt.assert_almost_equal(loss.item(), 0.0)
loss = gan_loss(input_2, False, is_disc=True)
npt.assert_almost_equal(loss.item(), 3.0)
# smgan
mask = torch.ones(1, 3, 6, 6)
gan_loss = GANLoss(
'smgan', loss_weight=2.0, real_label_val=1.0, fake_label_val=0.0)
loss = gan_loss(input_2, True, is_disc=False, mask=mask)
npt.assert_almost_equal(loss.item(), 2.0)
loss = gan_loss(input_2, False, is_disc=False, mask=mask)
npt.assert_almost_equal(loss.item(), 8.0)
loss = gan_loss(input_2, True, is_disc=True, mask=mask)
npt.assert_almost_equal(loss.item(), 1.0)
loss = gan_loss(input_2, False, is_disc=True, mask=mask)
npt.assert_almost_equal(loss.item(), 3.786323, decimal=6)
mask = torch.ones(1, 3, 6, 5)
loss = gan_loss(input_2, True, is_disc=False, mask=mask)
npt.assert_almost_equal(loss.item(), 2.0)
if torch.cuda.is_available():
input_2 = input_2.cuda()
mask = torch.ones(1, 3, 6, 6).cuda()
gan_loss = GANLoss(
'smgan', loss_weight=2.0, real_label_val=1.0, fake_label_val=0.0)
loss = gan_loss(input_2, True, is_disc=False, mask=mask)
npt.assert_almost_equal(loss.item(), 2.0)
loss = gan_loss(input_2, False, is_disc=False, mask=mask)
npt.assert_almost_equal(loss.item(), 8.0)
loss = gan_loss(input_2, True, is_disc=True, mask=mask)
npt.assert_almost_equal(loss.item(), 1.0)
loss = gan_loss(input_2, False, is_disc=True, mask=mask)
npt.assert_almost_equal(loss.item(), 3.786323, decimal=6)
# test GaussianBlur for smgan
with pytest.raises(TypeError):
gausian_blur = GaussianBlur(kernel_size=71, sigma=2)
gausian_blur(mask).detach().cpu()
with pytest.raises(TypeError):
gausian_blur = GaussianBlur(kernel_size=(70, 70))
gausian_blur(mask).detach().cpu()
with pytest.raises(TypeError):
mask = numpy.ones((1, 3, 6, 6))
gausian_blur = GaussianBlur()
gausian_blur(mask).detach().cpu()
with pytest.raises(ValueError):
mask = torch.ones(1, 3)
gausian_blur = GaussianBlur()
gausian_blur(mask).detach().cpu()
def test_gradient_penalty_losses():
"""Test gradient penalty losses."""
input = torch.ones(1, 3, 6, 6) * 2
gan_loss = GradientPenaltyLoss(loss_weight=10.0)
loss = gan_loss(lambda x: x, input, input, mask=None)
assert loss.item() > 0
mask = torch.ones(1, 3, 6, 6)
mask[:, :, 2:4, 2:4] = 0
loss = gan_loss(lambda x: x, input, input, mask=mask)
assert loss.item() > 0
def test_disc_shift_loss():
loss_disc_shift = DiscShiftLoss()
x = torch.Tensor([0.1])
loss = loss_disc_shift(x)
npt.assert_almost_equal(loss.item(), 0.001)
def test_gradient_loss():
with pytest.raises(ValueError):
# only 'none', 'mean' and 'sum' are supported
GradientLoss(reduction='InvalidValue')
unknown_h, unknown_w = (32, 32)
weight = torch.zeros(1, 1, 64, 64)
weight[0, 0, :unknown_h, :unknown_w] = 1
pred = weight.clone()
target = weight.clone() * 2
gradient_loss = GradientLoss(loss_weight=1.0, reduction='mean')
loss = gradient_loss(pred, target)
assert loss.shape == ()
npt.assert_almost_equal(loss.item(), 0.1860352)
gradient_loss = GradientLoss(loss_weight=0.5, reduction='none')
loss = gradient_loss(pred, target, weight)
assert loss.shape == (1, 1, 64, 64)
npt.assert_almost_equal(torch.sum(loss).item(), 252)
gradient_loss = GradientLoss(loss_weight=0.5, reduction='sum')
loss = gradient_loss(pred, target, weight)
assert loss.shape == ()
npt.assert_almost_equal(loss.item(), 252)
| 18,730 | 34.542694 | 79 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_losses/test_feature_loss.py | # Copyright (c) OpenMMLab. All rights reserved.
import pytest
import torch
from mmedit.models.losses import LightCNNFeatureLoss
def test_light_cnn_feature_loss():
pretrained = 'https://download.openmmlab.com/mmediting/' + \
'restorers/dic/light_cnn_feature.pth'
pred = torch.rand((3, 3, 128, 128))
gt = torch.rand((3, 3, 128, 128))
feature_loss = LightCNNFeatureLoss(pretrained=pretrained)
loss = feature_loss(pred, gt)
assert loss.item() > 0
feature_loss = LightCNNFeatureLoss(pretrained=pretrained, criterion='mse')
loss = feature_loss(pred, gt)
assert loss.item() > 0
if torch.cuda.is_available():
pred = pred.cuda()
gt = gt.cuda()
feature_loss = feature_loss.cuda()
pred.requires_grad = True
loss = feature_loss(pred, gt)
assert loss.item() > 0
optim = torch.optim.SGD(params=[pred], lr=10)
optim.zero_grad()
loss.backward()
optim.step()
loss_new = feature_loss(pred, gt)
assert loss_new < loss
feature_loss = LightCNNFeatureLoss(
pretrained=pretrained, criterion='mse').cuda()
loss = feature_loss(pred, gt)
assert loss.item() > 0
with pytest.raises(AssertionError):
feature_loss.model.train()
feature_loss(pred, gt)
# test criterion value error
with pytest.raises(ValueError):
LightCNNFeatureLoss(pretrained=pretrained, criterion='l2')
# test assert isinstance(pretrained, str)
with pytest.raises(AssertionError):
LightCNNFeatureLoss(pretrained=None)
| 1,600 | 28.648148 | 78 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_common/test_common_module.py | # Copyright (c) OpenMMLab. All rights reserved.
import pytest
import torch
import torch.nn as nn
from mmedit.models.common import (ASPP, DepthwiseSeparableConvModule,
GCAModule, LinearModule, MaskConvModule,
PartialConv2d, SimpleGatedConvModule)
def test_mask_conv_module():
with pytest.raises(KeyError):
# conv_cfg must be a dict or None
conv_cfg = dict(type='conv')
MaskConvModule(3, 8, 2, conv_cfg=conv_cfg)
with pytest.raises(AssertionError):
# norm_cfg must be a dict or None
norm_cfg = ['norm']
MaskConvModule(3, 8, 2, norm_cfg=norm_cfg)
with pytest.raises(AssertionError):
# order elements must be ('conv', 'norm', 'act')
order = ['conv', 'norm', 'act']
MaskConvModule(3, 8, 2, order=order)
with pytest.raises(AssertionError):
# order elements must be ('conv', 'norm', 'act')
order = ('conv', 'norm')
MaskConvModule(3, 8, 2, order=order)
with pytest.raises(KeyError):
# softmax is not supported
act_cfg = dict(type='softmax')
MaskConvModule(3, 8, 2, act_cfg=act_cfg)
conv_cfg = dict(type='PConv', multi_channel=True)
conv = MaskConvModule(3, 8, 2, conv_cfg=conv_cfg)
x = torch.rand(1, 3, 256, 256)
mask_in = torch.ones_like(x)
mask_in[..., 20:130, 120:150] = 0.
output, mask_update = conv(x, mask_in)
assert output.shape == (1, 8, 255, 255)
assert mask_update.shape == (1, 8, 255, 255)
# add test for ['norm', 'conv', 'act']
conv = MaskConvModule(
3, 8, 2, order=('norm', 'conv', 'act'), conv_cfg=conv_cfg)
x = torch.rand(1, 3, 256, 256)
output = conv(x, mask_in, return_mask=False)
assert output.shape == (1, 8, 255, 255)
conv = MaskConvModule(
3, 8, 3, padding=1, conv_cfg=conv_cfg, with_spectral_norm=True)
assert hasattr(conv.conv, 'weight_orig')
output = conv(x, return_mask=False)
assert output.shape == (1, 8, 256, 256)
conv = MaskConvModule(
3,
8,
3,
padding=1,
norm_cfg=dict(type='BN'),
padding_mode='reflect',
conv_cfg=conv_cfg)
assert isinstance(conv.padding_layer, nn.ReflectionPad2d)
output = conv(x, mask_in, return_mask=False)
assert output.shape == (1, 8, 256, 256)
conv = MaskConvModule(
3, 8, 3, padding=1, act_cfg=dict(type='LeakyReLU'), conv_cfg=conv_cfg)
output = conv(x, mask_in, return_mask=False)
assert output.shape == (1, 8, 256, 256)
with pytest.raises(KeyError):
conv = MaskConvModule(3, 8, 3, padding=1, padding_mode='igccc')
def test_pconv2d():
pconv2d = PartialConv2d(
3, 2, kernel_size=1, stride=1, multi_channel=True, eps=1e-8)
x = torch.rand(1, 3, 6, 6)
mask = torch.ones_like(x)
mask[..., 2, 2] = 0.
output, updated_mask = pconv2d(x, mask=mask)
assert output.shape == (1, 2, 6, 6)
assert updated_mask.shape == (1, 2, 6, 6)
output = pconv2d(x, mask=None)
assert output.shape == (1, 2, 6, 6)
pconv2d = PartialConv2d(
3, 2, kernel_size=1, stride=1, multi_channel=True, eps=1e-8)
output = pconv2d(x, mask=None)
assert output.shape == (1, 2, 6, 6)
pconv2d = PartialConv2d(
3, 2, kernel_size=1, stride=1, multi_channel=False, eps=1e-8)
output = pconv2d(x, mask=None)
assert output.shape == (1, 2, 6, 6)
pconv2d = PartialConv2d(
3,
2,
kernel_size=1,
stride=1,
bias=False,
multi_channel=True,
eps=1e-8)
output = pconv2d(x, mask=mask, return_mask=False)
assert output.shape == (1, 2, 6, 6)
with pytest.raises(AssertionError):
pconv2d(x, mask=torch.ones(1, 1, 6, 6))
pconv2d = PartialConv2d(
3,
2,
kernel_size=1,
stride=1,
bias=False,
multi_channel=False,
eps=1e-8)
output = pconv2d(x, mask=None)
assert output.shape == (1, 2, 6, 6)
with pytest.raises(AssertionError):
output = pconv2d(x, mask=mask[0])
with pytest.raises(AssertionError):
output = pconv2d(x, mask=torch.ones(1, 3, 6, 6))
if torch.cuda.is_available():
pconv2d = PartialConv2d(
3,
2,
kernel_size=1,
stride=1,
bias=False,
multi_channel=False,
eps=1e-8).cuda().half()
output = pconv2d(x.cuda().half(), mask=None)
assert output.shape == (1, 2, 6, 6)
def test_depthwise_separable_conv():
with pytest.raises(AssertionError):
# conv_cfg must be a dict or None
DepthwiseSeparableConvModule(4, 8, 2, groups=2)
# test default config
conv = DepthwiseSeparableConvModule(3, 8, 2)
assert conv.depthwise_conv.conv.groups == 3
assert conv.pointwise_conv.conv.kernel_size == (1, 1)
assert not conv.depthwise_conv.with_norm
assert not conv.pointwise_conv.with_norm
assert conv.depthwise_conv.activate.__class__.__name__ == 'ReLU'
assert conv.pointwise_conv.activate.__class__.__name__ == 'ReLU'
x = torch.rand(1, 3, 256, 256)
output = conv(x)
assert output.shape == (1, 8, 255, 255)
# test
conv = DepthwiseSeparableConvModule(3, 8, 2, dw_norm_cfg=dict(type='BN'))
assert conv.depthwise_conv.norm_name == 'bn'
assert not conv.pointwise_conv.with_norm
x = torch.rand(1, 3, 256, 256)
output = conv(x)
assert output.shape == (1, 8, 255, 255)
conv = DepthwiseSeparableConvModule(3, 8, 2, pw_norm_cfg=dict(type='BN'))
assert not conv.depthwise_conv.with_norm
assert conv.pointwise_conv.norm_name == 'bn'
x = torch.rand(1, 3, 256, 256)
output = conv(x)
assert output.shape == (1, 8, 255, 255)
# add test for ['norm', 'conv', 'act']
conv = DepthwiseSeparableConvModule(3, 8, 2, order=('norm', 'conv', 'act'))
x = torch.rand(1, 3, 256, 256)
output = conv(x)
assert output.shape == (1, 8, 255, 255)
conv = DepthwiseSeparableConvModule(
3, 8, 3, padding=1, with_spectral_norm=True)
assert hasattr(conv.depthwise_conv.conv, 'weight_orig')
assert hasattr(conv.pointwise_conv.conv, 'weight_orig')
output = conv(x)
assert output.shape == (1, 8, 256, 256)
conv = DepthwiseSeparableConvModule(
3, 8, 3, padding=1, padding_mode='reflect')
assert isinstance(conv.depthwise_conv.padding_layer, nn.ReflectionPad2d)
output = conv(x)
assert output.shape == (1, 8, 256, 256)
conv = DepthwiseSeparableConvModule(
3, 8, 3, padding=1, dw_act_cfg=dict(type='LeakyReLU'))
assert conv.depthwise_conv.activate.__class__.__name__ == 'LeakyReLU'
assert conv.pointwise_conv.activate.__class__.__name__ == 'ReLU'
output = conv(x)
assert output.shape == (1, 8, 256, 256)
conv = DepthwiseSeparableConvModule(
3, 8, 3, padding=1, pw_act_cfg=dict(type='LeakyReLU'))
assert conv.depthwise_conv.activate.__class__.__name__ == 'ReLU'
assert conv.pointwise_conv.activate.__class__.__name__ == 'LeakyReLU'
output = conv(x)
assert output.shape == (1, 8, 256, 256)
def test_aspp():
# test aspp with normal conv
aspp = ASPP(128, out_channels=512, mid_channels=128, dilations=(6, 12, 18))
assert aspp.convs[0].activate.__class__.__name__ == 'ReLU'
assert aspp.convs[0].conv.out_channels == 128
assert aspp.convs[1].__class__.__name__ == 'ConvModule'
for conv_idx in range(1, 4):
assert aspp.convs[conv_idx].conv.dilation[0] == 6 * conv_idx
x = torch.rand(2, 128, 8, 8)
output = aspp(x)
assert output.shape == (2, 512, 8, 8)
# test aspp with separable conv
aspp = ASPP(128, separable_conv=True)
assert aspp.convs[1].__class__.__name__ == 'DepthwiseSeparableConvModule'
x = torch.rand(2, 128, 8, 8)
output = aspp(x)
assert output.shape == (2, 256, 8, 8)
# test aspp with ReLU6
aspp = ASPP(128, dilations=(12, 24, 36), act_cfg=dict(type='ReLU6'))
assert aspp.convs[0].activate.__class__.__name__ == 'ReLU6'
for conv_idx in range(1, 4):
assert aspp.convs[conv_idx].conv.dilation[0] == 12 * conv_idx
x = torch.rand(2, 128, 8, 8)
output = aspp(x)
assert output.shape == (2, 256, 8, 8)
def test_gca_module():
img_feat = torch.rand(1, 128, 64, 64)
alpha_feat = torch.rand(1, 128, 64, 64)
unknown = None
gca = GCAModule(128, 128, rate=1)
output = gca(img_feat, alpha_feat, unknown)
assert output.shape == (1, 128, 64, 64)
img_feat = torch.rand(1, 128, 64, 64)
alpha_feat = torch.rand(1, 128, 64, 64)
unknown = torch.rand(1, 1, 64, 64)
gca = GCAModule(128, 128, rate=2)
output = gca(img_feat, alpha_feat, unknown)
assert output.shape == (1, 128, 64, 64)
def test_gated_conv():
conv = SimpleGatedConvModule(3, 10, 3, padding=1)
x = torch.rand((2, 3, 10, 10))
assert not conv.conv.with_activation
assert conv.with_feat_act
assert conv.with_gate_act
assert isinstance(conv.feat_act, nn.ELU)
assert isinstance(conv.gate_act, nn.Sigmoid)
assert conv.conv.out_channels == 20
out = conv(x)
assert out.shape == (2, 10, 10, 10)
conv = SimpleGatedConvModule(
3, 10, 3, padding=1, feat_act_cfg=None, gate_act_cfg=None)
assert not conv.with_gate_act
out = conv(x)
assert out.shape == (2, 10, 10, 10)
with pytest.raises(AssertionError):
conv = SimpleGatedConvModule(
3, 1, 3, padding=1, order=('linear', 'act', 'norm'))
conv = SimpleGatedConvModule(3, out_channels=10, kernel_size=3, padding=1)
assert conv.conv.out_channels == 20
out = conv(x)
assert out.shape == (2, 10, 10, 10)
def test_linear_module():
linear = LinearModule(10, 20)
linear.init_weights()
x = torch.rand((3, 10))
assert linear.with_bias
assert not linear.with_spectral_norm
assert linear.out_features == 20
assert linear.in_features == 10
assert isinstance(linear.activate, nn.ReLU)
y = linear(x)
assert y.shape == (3, 20)
linear = LinearModule(10, 20, act_cfg=None, with_spectral_norm=True)
assert hasattr(linear.linear, 'weight_orig')
assert not linear.with_activation
y = linear(x)
assert y.shape == (3, 20)
linear = LinearModule(
10, 20, act_cfg=dict(type='LeakyReLU'), with_spectral_norm=True)
y = linear(x)
assert y.shape == (3, 20)
assert isinstance(linear.activate, nn.LeakyReLU)
linear = LinearModule(
10, 20, bias=False, act_cfg=None, with_spectral_norm=True)
y = linear(x)
assert y.shape == (3, 20)
assert not linear.with_bias
linear = LinearModule(
10,
20,
bias=False,
act_cfg=None,
with_spectral_norm=True,
order=('act', 'linear'))
assert linear.order == ('act', 'linear')
| 10,851 | 31.984802 | 79 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_common/test_img_normalize.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch
from mmedit.models.common import ImgNormalize
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_mean)
rgb_std = torch.tensor(rgb_std)
mean_x = x.mean(dim=1)
mean_y = y.mean(dim=1)
std_x = x.std(dim=1)
std_y = y.std(dim=1)
assert sum(torch.div(std_x, std_y) - rgb_std) < 1e-5
assert sum(torch.div(mean_x - rgb_mean, rgb_std) - mean_y) < 1e-5
| 695 | 29.26087 | 69 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_common/test_sampling.py | # Copyright (c) OpenMMLab. All rights reserved.
import pytest
import torch
from mmedit.models.common import PixelShufflePack, pixel_unshuffle
def test_pixel_shuffle():
# test on cpu
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)
# test on gpu
if torch.cuda.is_available():
model = model.cuda()
x = x.cuda()
y = model(x)
assert y.shape == (1, 3, 32, 32)
def test_pixel_unshuffle():
# test on cpu
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)
# test on gpu
if torch.cuda.is_available():
x = x.cuda()
y = pixel_unshuffle(x, scale=2)
assert y.shape == (1, 12, 10, 10)
with pytest.raises(AssertionError):
y = pixel_unshuffle(x, scale=3)
| 988 | 23.121951 | 66 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_common/test_flow_warp.py | # Copyright (c) OpenMMLab. All rights reserved.
import pytest
import torch
from mmedit.models import flow_warp
def tensor_shift(x, shift=(1, 1), fill_val=0):
"""Shift tensor for testing flow_warp.
Args:
x (Tensor): the input tensor. The shape is (b, c, h, w].
shift (tuple): shift pixel.
fill_val (float): fill value.
Returns:
Tensor: the shifted tensor.
"""
_, _, h, w = x.size()
shift_h, shift_w = shift
new = torch.ones_like(x) * fill_val
len_h = h - shift_h
len_w = w - shift_w
new[:, :, shift_h:shift_h + len_h,
shift_w:shift_w + len_w] = x.narrow(2, 0, len_h).narrow(3, 0, len_w)
return new
def test_flow_warp():
x = torch.rand(1, 3, 10, 10)
flow = torch.rand(1, 4, 4, 2)
with pytest.raises(ValueError):
# The spatial sizes of input and flow are not the same.
flow_warp(x, flow)
# cpu
x = torch.rand(1, 3, 10, 10)
flow = -torch.ones(1, 10, 10, 2)
result = flow_warp(x, flow)
assert result.size() == (1, 3, 10, 10)
error = torch.sum(torch.abs(result - tensor_shift(x, (1, 1))))
assert error < 1e-5
# gpu
if torch.cuda.is_available():
x = torch.rand(1, 3, 10, 10).cuda()
flow = -torch.ones(1, 10, 10, 2).cuda()
result = flow_warp(x, flow)
assert result.size() == (1, 3, 10, 10)
error = torch.sum(torch.abs(result - tensor_shift(x, (1, 1))))
assert error < 1e-5
| 1,471 | 26.773585 | 76 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_common/test_model_utils.py | # Copyright (c) OpenMMLab. All rights reserved.
import copy
import numpy as np
import pytest
import torch
import torch.nn as nn
from mmedit.models.common import (GANImageBuffer, extract_around_bbox,
extract_bbox_patch, generation_init_weights,
set_requires_grad)
def test_set_requires_grad():
model = torch.nn.Conv2d(1, 3, 1, 1)
set_requires_grad(model, False)
for param in model.parameters():
assert not param.requires_grad
def test_gan_image_buffer():
# test buffer size = 0
buffer = GANImageBuffer(buffer_size=0)
img_np = np.random.randn(1, 3, 256, 256)
img_tensor = torch.from_numpy(img_np)
img_tensor_return = buffer.query(img_tensor)
assert torch.equal(img_tensor_return, img_tensor)
# test buffer size > 0
buffer = GANImageBuffer(buffer_size=1)
img_np = np.random.randn(2, 3, 256, 256)
img_tensor = torch.from_numpy(img_np)
img_tensor_0 = torch.unsqueeze(img_tensor[0], 0)
img_tensor_1 = torch.unsqueeze(img_tensor[1], 0)
img_tensor_00 = torch.cat([img_tensor_0, img_tensor_0], 0)
img_tensor_return = buffer.query(img_tensor)
assert (torch.equal(img_tensor_return, img_tensor)
and torch.equal(buffer.image_buffer[0], img_tensor_0)) or \
(torch.equal(img_tensor_return, img_tensor_00)
and torch.equal(buffer.image_buffer[0], img_tensor_1))
# test buffer size > 0, specify buffer chance
buffer = GANImageBuffer(buffer_size=1, buffer_ratio=0.3)
img_np = np.random.randn(2, 3, 256, 256)
img_tensor = torch.from_numpy(img_np)
img_tensor_0 = torch.unsqueeze(img_tensor[0], 0)
img_tensor_1 = torch.unsqueeze(img_tensor[1], 0)
img_tensor_00 = torch.cat([img_tensor_0, img_tensor_0], 0)
img_tensor_return = buffer.query(img_tensor)
assert (torch.equal(img_tensor_return, img_tensor)
and torch.equal(buffer.image_buffer[0], img_tensor_0)) or \
(torch.equal(img_tensor_return, img_tensor_00)
and torch.equal(buffer.image_buffer[0], img_tensor_1))
def test_generation_init_weights():
# Conv
module = nn.Conv2d(3, 3, 1)
module_tmp = copy.deepcopy(module)
generation_init_weights(module, init_type='normal', init_gain=0.02)
generation_init_weights(module, init_type='xavier', init_gain=0.02)
generation_init_weights(module, init_type='kaiming')
generation_init_weights(module, init_type='orthogonal', init_gain=0.02)
with pytest.raises(NotImplementedError):
generation_init_weights(module, init_type='abc')
assert not torch.equal(module.weight.data, module_tmp.weight.data)
# Linear
module = nn.Linear(3, 1)
module_tmp = copy.deepcopy(module)
generation_init_weights(module, init_type='normal', init_gain=0.02)
generation_init_weights(module, init_type='xavier', init_gain=0.02)
generation_init_weights(module, init_type='kaiming')
generation_init_weights(module, init_type='orthogonal', init_gain=0.02)
with pytest.raises(NotImplementedError):
generation_init_weights(module, init_type='abc')
assert not torch.equal(module.weight.data, module_tmp.weight.data)
# BatchNorm2d
module = nn.BatchNorm2d(3)
module_tmp = copy.deepcopy(module)
generation_init_weights(module, init_type='normal', init_gain=0.02)
assert not torch.equal(module.weight.data, module_tmp.weight.data)
def test_extract_bbox_patch():
img_np = np.random.randn(100, 100, 3)
bbox = np.asarray([10, 10, 10, 10])
img_patch = extract_bbox_patch(bbox, img_np, channel_first=False)
assert np.array_equal(img_patch, img_np[10:20, 10:20, ...])
img_np = np.random.randn(1, 3, 100, 100)
bbox = np.asarray([[10, 10, 10, 10]])
img_patch = extract_bbox_patch(bbox, img_np)
assert np.array_equal(img_patch, img_np[..., 10:20, 10:20])
img_tensor = torch.from_numpy(img_np)
bbox = np.asarray([[10, 10, 10, 10]])
img_patch = extract_bbox_patch(bbox, img_tensor)
assert np.array_equal(img_patch.numpy(), img_np[..., 10:20, 10:20])
with pytest.raises(AssertionError):
img_np = np.random.randn(100, 100)
bbox = np.asarray([[10, 10, 10, 10]])
img_patch = extract_bbox_patch(bbox, img_np)
with pytest.raises(AssertionError):
img_np = np.random.randn(2, 3, 100, 100)
bbox = np.asarray([[10, 10, 10, 10]])
img_patch = extract_bbox_patch(bbox, img_np)
with pytest.raises(AssertionError):
img_np = np.random.randn(3, 100, 100)
bbox = np.asarray([[10, 10, 10, 10]])
img_patch = extract_bbox_patch(bbox, img_np)
def test_extract_around_bbox():
with pytest.raises(AssertionError):
img_np = np.random.randn(100, 100, 3)
bbox = np.asarray([10, 10, 10, 10])
extract_around_bbox(img_np, bbox, (4, 4))
with pytest.raises(TypeError):
bbox = dict(test='fail')
img_np = np.random.randn(100, 100, 3)
extract_around_bbox(img_np, bbox, (15, 15))
img_np = np.random.randn(100, 100, 3)
bbox = np.asarray([10, 10, 10, 10])
img_new, bbox_new = extract_around_bbox(
img_np, bbox, (14, 14), channel_first=False)
assert np.array_equal(img_np[8:22, 8:22, ...], img_new)
assert np.array_equal(bbox_new, np.asarray([8, 8, 14, 14]))
img_np = np.random.randn(1, 3, 100, 100)
bbox = np.asarray([[10, 10, 10, 10]])
img_tensor = torch.from_numpy(img_np)
bbox_tensor = torch.from_numpy(bbox)
img_new, bbox_new = extract_around_bbox(
img_tensor, bbox_tensor, target_size=[14, 14])
assert np.array_equal(img_np[..., 8:22, 8:22], img_new.numpy())
assert np.array_equal(bbox_new.numpy(), np.asarray([[8, 8, 14, 14]]))
| 5,756 | 38.979167 | 78 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_common/test_ensemble.py | # Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
import pytest
import torch
import torch.nn as nn
from mmedit.models.common import SpatialTemporalEnsemble
def test_ensemble_cpu():
model = nn.Identity()
# spatial ensemble of an image
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())
# spatial ensemble of a sequence
ensemble = SpatialTemporalEnsemble(is_temporal_ensemble=False)
inputs = torch.rand(1, 2, 3, 4, 4)
outputs = ensemble(inputs, model)
np.testing.assert_almost_equal(inputs.numpy(), outputs.numpy())
# spatial and temporal ensemble of a sequence
ensemble = SpatialTemporalEnsemble(is_temporal_ensemble=True)
inputs = torch.rand(1, 2, 3, 4, 4)
outputs = ensemble(inputs, model)
np.testing.assert_almost_equal(inputs.numpy(), outputs.numpy())
# spatial and temporal ensemble of an image
with pytest.raises(ValueError):
ensemble = SpatialTemporalEnsemble(is_temporal_ensemble=True)
inputs = torch.rand(1, 3, 4, 4)
outputs = ensemble(inputs, model)
def test_ensemble_cuda():
if torch.cuda.is_available():
model = nn.Identity().cuda()
# spatial ensemble of an image
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(),
outputs.cpu().numpy())
# spatial ensemble of a sequence
ensemble = SpatialTemporalEnsemble(is_temporal_ensemble=False)
inputs = torch.rand(1, 2, 3, 4, 4).cuda()
outputs = ensemble(inputs, model)
np.testing.assert_almost_equal(inputs.cpu().numpy(),
outputs.cpu().numpy())
# spatial and temporal ensemble of a sequence
ensemble = SpatialTemporalEnsemble(is_temporal_ensemble=True)
inputs = torch.rand(1, 2, 3, 4, 4).cuda()
outputs = ensemble(inputs, model)
np.testing.assert_almost_equal(inputs.cpu().numpy(),
outputs.cpu().numpy())
# spatial and temporal ensemble of an image
with pytest.raises(ValueError):
ensemble = SpatialTemporalEnsemble(is_temporal_ensemble=True)
inputs = torch.rand(1, 3, 4, 4).cuda()
outputs = ensemble(inputs, model)
| 2,575 | 36.882353 | 73 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_transformer/test_search_transformer.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch
from mmedit.models.builder import build_component
def test_search_transformer():
model_cfg = dict(type='SearchTransformer')
model = build_component(model_cfg)
lr_pad_level3 = torch.randn((2, 32, 32, 32))
ref_pad_level3 = torch.randn((2, 32, 32, 32))
ref_level3 = torch.randn((2, 32, 32, 32))
ref_level2 = torch.randn((2, 16, 64, 64))
ref_level1 = torch.randn((2, 8, 128, 128))
s, textures = model(lr_pad_level3, ref_pad_level3,
(ref_level3, ref_level2, ref_level1))
t_level3, t_level2, t_level1 = textures
assert s.shape == (2, 1, 32, 32)
assert t_level3.shape == (2, 32, 32, 32)
assert t_level2.shape == (2, 16, 64, 64)
assert t_level1.shape == (2, 8, 128, 128)
| 806 | 31.28 | 61 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_components/test_stylegan2.py | # Copyright (c) OpenMMLab. All rights reserved.
from copy import deepcopy
import pytest
import torch
import torch.nn as nn
from mmedit.models.components.stylegan2.common import get_module_device
from mmedit.models.components.stylegan2.generator_discriminator import (
StyleGAN2Discriminator, StyleGANv2Generator)
from mmedit.models.components.stylegan2.modules import (Blur,
ModulatedStyleConv,
ModulatedToRGB)
class TestBlur:
@classmethod
def setup_class(cls):
cls.kernel = [1, 3, 3, 1]
cls.pad = (1, 1)
@pytest.mark.skipif(not torch.cuda.is_available(), reason='requires cuda')
def test_blur_cuda(self):
blur = Blur(self.kernel, self.pad)
x = torch.randn((2, 3, 8, 8))
res = blur(x)
assert res.shape == (2, 3, 7, 7)
class TestModStyleConv:
@classmethod
def setup_class(cls):
cls.default_cfg = dict(
in_channels=3,
out_channels=1,
kernel_size=3,
style_channels=5,
upsample=True)
def test_mod_styleconv_cpu(self):
conv = ModulatedStyleConv(**self.default_cfg)
input_x = torch.randn((2, 3, 4, 4))
input_style = torch.randn((2, 5))
res = conv(input_x, input_style)
assert res.shape == (2, 1, 8, 8)
_cfg = deepcopy(self.default_cfg)
_cfg['upsample'] = False
conv = ModulatedStyleConv(**_cfg)
input_x = torch.randn((2, 3, 4, 4))
input_style = torch.randn((2, 5))
res = conv(input_x, input_style)
assert res.shape == (2, 1, 4, 4)
@pytest.mark.skipif(not torch.cuda.is_available(), reason='requires cuda')
def test_mod_styleconv_cuda(self):
conv = ModulatedStyleConv(**self.default_cfg).cuda()
input_x = torch.randn((2, 3, 4, 4)).cuda()
input_style = torch.randn((2, 5)).cuda()
res = conv(input_x, input_style)
assert res.shape == (2, 1, 8, 8)
_cfg = deepcopy(self.default_cfg)
_cfg['upsample'] = False
conv = ModulatedStyleConv(**_cfg).cuda()
input_x = torch.randn((2, 3, 4, 4)).cuda()
input_style = torch.randn((2, 5)).cuda()
res = conv(input_x, input_style)
assert res.shape == (2, 1, 4, 4)
class TestToRGB:
@classmethod
def setup_class(cls):
cls.default_cfg = dict(in_channels=5, style_channels=5, out_channels=3)
def test_torgb_cpu(self):
model = ModulatedToRGB(**self.default_cfg)
input_x = torch.randn((2, 5, 4, 4))
style = torch.randn((2, 5))
res = model(input_x, style)
assert res.shape == (2, 3, 4, 4)
input_x = torch.randn((2, 5, 8, 8))
style = torch.randn((2, 5))
skip = torch.randn(2, 3, 4, 4)
res = model(input_x, style, skip)
assert res.shape == (2, 3, 8, 8)
@pytest.mark.skipif(not torch.cuda.is_available(), reason='requires cuda')
def test_torgb_cuda(self):
model = ModulatedToRGB(**self.default_cfg).cuda()
input_x = torch.randn((2, 5, 4, 4)).cuda()
style = torch.randn((2, 5)).cuda()
res = model(input_x, style)
assert res.shape == (2, 3, 4, 4)
input_x = torch.randn((2, 5, 8, 8)).cuda()
style = torch.randn((2, 5)).cuda()
skip = torch.randn(2, 3, 4, 4).cuda()
res = model(input_x, style, skip)
assert res.shape == (2, 3, 8, 8)
class TestStyleGAN2Generator:
@classmethod
def setup_class(cls):
cls.default_cfg = dict(
out_size=64, style_channels=16, num_mlps=4, channel_multiplier=1)
def test_stylegan2_g_cpu(self):
# test default config
g = StyleGANv2Generator(**self.default_cfg)
res = g(None, num_batches=2)
assert res.shape == (2, 3, 64, 64)
truncation_mean = g.get_mean_latent()
res = g(
None,
num_batches=2,
randomize_noise=False,
truncation=0.7,
truncation_latent=truncation_mean)
assert res.shape == (2, 3, 64, 64)
res = g.style_mixing(2, 2, truncation_latent=truncation_mean)
assert res.shape[2] == 64
random_noise = g.make_injected_noise()
res = g(
None,
num_batches=1,
injected_noise=random_noise,
randomize_noise=False)
assert res.shape == (1, 3, 64, 64)
random_noise = g.make_injected_noise()
res = g(
None, num_batches=1, injected_noise=None, randomize_noise=False)
assert res.shape == (1, 3, 64, 64)
styles = [torch.randn((1, 16)) for _ in range(2)]
res = g(
styles, num_batches=1, injected_noise=None, randomize_noise=False)
assert res.shape == (1, 3, 64, 64)
res = g(
torch.randn,
num_batches=1,
injected_noise=None,
randomize_noise=False)
assert res.shape == (1, 3, 64, 64)
g.eval()
assert g.default_style_mode == 'single'
g.train()
assert g.default_style_mode == 'mix'
with pytest.raises(AssertionError):
styles = [torch.randn((1, 6)) for _ in range(2)]
_ = g(styles, injected_noise=None, randomize_noise=False)
cfg_ = deepcopy(self.default_cfg)
cfg_['out_size'] = 256
g = StyleGANv2Generator(**cfg_)
res = g(None, num_batches=2)
assert res.shape == (2, 3, 256, 256)
@pytest.mark.skipif(not torch.cuda.is_available(), reason='requires cuda')
def test_g_cuda(self):
# test default config
g = StyleGANv2Generator(**self.default_cfg).cuda()
res = g(None, num_batches=2)
assert res.shape == (2, 3, 64, 64)
random_noise = g.make_injected_noise()
res = g(
None,
num_batches=1,
injected_noise=random_noise,
randomize_noise=False)
assert res.shape == (1, 3, 64, 64)
random_noise = g.make_injected_noise()
res = g(
None, num_batches=1, injected_noise=None, randomize_noise=False)
assert res.shape == (1, 3, 64, 64)
styles = [torch.randn((1, 16)).cuda() for _ in range(2)]
res = g(
styles, num_batches=1, injected_noise=None, randomize_noise=False)
assert res.shape == (1, 3, 64, 64)
res = g(
torch.randn,
num_batches=1,
injected_noise=None,
randomize_noise=False)
assert res.shape == (1, 3, 64, 64)
g.eval()
assert g.default_style_mode == 'single'
g.train()
assert g.default_style_mode == 'mix'
with pytest.raises(AssertionError):
styles = [torch.randn((1, 6)).cuda() for _ in range(2)]
_ = g(styles, injected_noise=None, randomize_noise=False)
cfg_ = deepcopy(self.default_cfg)
cfg_['out_size'] = 256
g = StyleGANv2Generator(**cfg_).cuda()
res = g(None, num_batches=2)
assert res.shape == (2, 3, 256, 256)
class TestStyleGANv2Disc:
@classmethod
def setup_class(cls):
cls.default_cfg = dict(in_size=64, channel_multiplier=1)
def test_stylegan2_disc_cpu(self):
d = StyleGAN2Discriminator(**self.default_cfg)
img = torch.randn((2, 3, 64, 64))
score = d(img)
assert score.shape == (2, 1)
@pytest.mark.skipif(not torch.cuda.is_available(), reason='requires cuda')
def test_stylegan2_disc_cuda(self):
d = StyleGAN2Discriminator(**self.default_cfg).cuda()
img = torch.randn((2, 3, 64, 64)).cuda()
score = d(img)
assert score.shape == (2, 1)
def test_get_module_device_cpu():
device = get_module_device(nn.Conv2d(3, 3, 3, 1, 1))
assert device == torch.device('cpu')
# The input module should contain parameters.
with pytest.raises(ValueError):
get_module_device(nn.Flatten())
@pytest.mark.skipif(not torch.cuda.is_available(), reason='requires cuda')
def test_get_module_device_cuda():
module = nn.Conv2d(3, 3, 3, 1, 1).cuda()
device = get_module_device(module)
assert device == next(module.parameters()).get_device()
# The input module should contain parameters.
with pytest.raises(ValueError):
get_module_device(nn.Flatten().cuda())
| 8,432 | 30.466418 | 79 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_components/test_refiners/test_mlp_refiner.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch
import torch.nn as nn
from mmedit.models.builder import build_component
def test_mlp_refiner():
model_cfg = dict(
type='MLPRefiner', in_dim=8, out_dim=3, hidden_list=[8, 8, 8, 8])
mlp = build_component(model_cfg)
# test attributes
assert mlp.__class__.__name__ == 'MLPRefiner'
# prepare data
inputs = torch.rand(2, 8)
targets = torch.rand(2, 3)
if torch.cuda.is_available():
inputs = inputs.cuda()
targets = targets.cuda()
mlp = mlp.cuda()
data_batch = {'in': inputs, 'target': targets}
# prepare optimizer
criterion = nn.L1Loss()
optimizer = torch.optim.Adam(mlp.parameters(), lr=1e-4)
# test train_step
output = mlp.forward(data_batch['in'])
assert output.shape == data_batch['target'].shape
loss = criterion(output, data_batch['target'])
optimizer.zero_grad()
loss.backward()
optimizer.step()
| 971 | 26.771429 | 73 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_components/test_refiners/test_matting_refiners.py | # Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
import torch
from mmedit.models import PlainRefiner
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_plain_refiner():
"""Test PlainRefiner."""
model = PlainRefiner()
model.init_weights()
model.train()
merged, alpha, trimap, raw_alpha = _demo_inputs_pair()
prediction = model(torch.cat([merged, raw_alpha.sigmoid()], 1), raw_alpha)
assert_tensor_with_shape(prediction, torch.Size([1, 1, 64, 64]))
# test forward with gpu
if torch.cuda.is_available():
model = PlainRefiner()
model.init_weights()
model.train()
model.cuda()
merged, alpha, trimap, raw_alpha = _demo_inputs_pair(cuda=True)
prediction = model(
torch.cat([merged, raw_alpha.sigmoid()], 1), raw_alpha)
assert_tensor_with_shape(prediction, torch.Size([1, 1, 64, 64]))
def _demo_inputs_pair(img_shape=(64, 64), batch_size=1, cuda=False):
"""
Create a superset of inputs needed to run refiner.
Args:
img_shape (tuple): shape of the input image.
batch_size (int): batch size of the input batch.
cuda (bool): whether transfer input into gpu.
"""
color_shape = (batch_size, 3, img_shape[0], img_shape[1])
gray_shape = (batch_size, 1, img_shape[0], img_shape[1])
merged = torch.from_numpy(np.random.random(color_shape).astype(np.float32))
alpha = torch.from_numpy(np.random.random(gray_shape).astype(np.float32))
trimap = torch.from_numpy(np.random.random(gray_shape).astype(np.float32))
raw_alpha = torch.from_numpy(
np.random.random(gray_shape).astype(np.float32))
if cuda:
merged = merged.cuda()
alpha = alpha.cuda()
trimap = trimap.cuda()
raw_alpha = raw_alpha.cuda()
return merged, alpha, trimap, raw_alpha
| 2,239 | 34.555556 | 79 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_components/test_refiners/test_deepfill_refiner.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch
from mmedit.models import (ContextualAttentionNeck, DeepFillDecoder,
DeepFillEncoder, DeepFillRefiner, GLDilationNeck)
def test_deepfill_refiner():
refiner = DeepFillRefiner()
x = torch.rand((2, 5, 256, 256))
mask = x.new_ones((2, 1, 256, 256))
mask[..., 30:100, 40:100] = 0.
res, offset = refiner(x, mask)
assert res.shape == (2, 3, 256, 256)
assert offset.shape == (2, 32, 32, 32, 32)
# check model architecture
assert isinstance(refiner.encoder_attention, DeepFillEncoder)
assert isinstance(refiner.encoder_conv, DeepFillEncoder)
assert isinstance(refiner.contextual_attention_neck,
ContextualAttentionNeck)
assert isinstance(refiner.decoder, DeepFillDecoder)
assert isinstance(refiner.dilation_neck, GLDilationNeck)
if torch.cuda.is_available():
refiner = DeepFillRefiner().cuda()
x = torch.rand((2, 5, 256, 256)).cuda()
res, offset = refiner(x, mask.cuda())
assert res.shape == (2, 3, 256, 256)
assert offset.shape == (2, 32, 32, 32, 32)
# check model architecture
assert isinstance(refiner.encoder_attention, DeepFillEncoder)
assert isinstance(refiner.encoder_conv, DeepFillEncoder)
assert isinstance(refiner.contextual_attention_neck,
ContextualAttentionNeck)
assert isinstance(refiner.decoder, DeepFillDecoder)
assert isinstance(refiner.dilation_neck, GLDilationNeck)
| 1,564 | 37.170732 | 76 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_components/test_discriminators/test_unet_disc.py | # Copyright (c) OpenMMLab. All rights reserved.
import pytest
import torch
from mmedit.models.components import UNetDiscriminatorWithSpectralNorm
def test_unet_disc_with_spectral_norm():
# cpu
disc = UNetDiscriminatorWithSpectralNorm(in_channels=3)
img = torch.randn(1, 3, 16, 16)
disc(img)
with pytest.raises(TypeError):
# pretrained must be a string path
disc.init_weights(pretrained=233)
# cuda
if torch.cuda.is_available():
disc = disc.cuda()
img = img.cuda()
disc(img)
with pytest.raises(TypeError):
# pretrained must be a string path
disc.init_weights(pretrained=233)
| 680 | 24.222222 | 70 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_components/test_discriminators/test_light_cnn.py | # Copyright (c) OpenMMLab. All rights reserved.
import pytest
import torch
from mmedit.models.builder import build_component
from mmedit.models.components.discriminators.light_cnn import MaxFeature
def test_max_feature():
# cpu
conv2d = MaxFeature(16, 16, filter_type='conv2d')
x1 = torch.rand(3, 16, 16, 16)
y1 = conv2d(x1)
assert y1.shape == (3, 16, 16, 16)
linear = MaxFeature(16, 16, filter_type='linear')
x2 = torch.rand(3, 16)
y2 = linear(x2)
assert y2.shape == (3, 16)
# gpu
if torch.cuda.is_available():
x1 = x1.cuda()
x2 = x2.cuda()
conv2d = conv2d.cuda()
linear = linear.cuda()
y1 = conv2d(x1)
assert y1.shape == (3, 16, 16, 16)
y2 = linear(x2)
assert y2.shape == (3, 16)
# filter_type should be conv2d or linear
with pytest.raises(ValueError):
MaxFeature(12, 12, filter_type='conv1d')
def test_light_cnn():
cfg = dict(type='LightCNN', in_channels=3)
net = build_component(cfg)
net.init_weights(pretrained=None)
# cpu
inputs = torch.rand((2, 3, 128, 128))
output = net(inputs)
assert output.shape == (2, 1)
# gpu
if torch.cuda.is_available():
net.init_weights(pretrained=None)
net = net.cuda()
output = net(inputs.cuda())
assert output.shape == (2, 1)
# pretrained should be str or None
with pytest.raises(TypeError):
net.init_weights(pretrained=[1])
| 1,475 | 27.384615 | 72 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_components/test_discriminators/test_discriminators.py | # Copyright (c) OpenMMLab. All rights reserved.
import copy
import numpy as np
import pytest
import torch
from mmedit.models import build_component
def test_ttsr_dict():
cfg = dict(type='TTSRDiscriminator', in_channels=3, in_size=160)
net = build_component(cfg)
net.init_weights(pretrained=None)
# cpu
inputs = torch.rand((2, 3, 160, 160))
output = net(inputs)
assert output.shape == (2, 1)
# gpu
if torch.cuda.is_available():
net.init_weights(pretrained=None)
net = net.cuda()
output = net(inputs.cuda())
assert output.shape == (2, 1)
# pretrained should be str or None
with pytest.raises(TypeError):
net.init_weights(pretrained=[1])
def test_patch_discriminator():
# color, BN
cfg = dict(
type='PatchDiscriminator',
in_channels=3,
base_channels=64,
num_conv=3,
norm_cfg=dict(type='BN'),
init_cfg=dict(type='normal', gain=0.02))
net = build_component(cfg)
net.init_weights(pretrained=None)
# cpu
input_shape = (1, 3, 64, 64)
img = _demo_inputs(input_shape)
output = net(img)
assert output.shape == (1, 1, 6, 6)
# gpu
if torch.cuda.is_available():
net.init_weights(pretrained=None)
net = net.cuda()
output = net(img.cuda())
assert output.shape == (1, 1, 6, 6)
# pretrained should be str or None
with pytest.raises(TypeError):
net.init_weights(pretrained=[1])
# gray, IN
cfg = dict(
type='PatchDiscriminator',
in_channels=1,
base_channels=64,
num_conv=3,
norm_cfg=dict(type='IN'),
init_cfg=dict(type='normal', gain=0.02))
net = build_component(cfg)
net.init_weights(pretrained=None)
# cpu
input_shape = (1, 1, 64, 64)
img = _demo_inputs(input_shape)
output = net(img)
assert output.shape == (1, 1, 6, 6)
# gpu
if torch.cuda.is_available():
net.init_weights(pretrained=None)
net = net.cuda()
output = net(img.cuda())
assert output.shape == (1, 1, 6, 6)
# pretrained should be str or None
with pytest.raises(TypeError):
net.init_weights(pretrained=[1])
# test norm_cfg assertions
bad_cfg = copy.deepcopy(cfg)
bad_cfg['norm_cfg'] = None
with pytest.raises(AssertionError):
_ = build_component(bad_cfg)
bad_cfg['norm_cfg'] = dict(tp='BN')
with pytest.raises(AssertionError):
_ = build_component(bad_cfg)
def test_smpatch_discriminator():
# color, BN
cfg = dict(
type='SoftMaskPatchDiscriminator',
in_channels=3,
base_channels=64,
num_conv=3,
with_spectral_norm=True)
net = build_component(cfg)
net.init_weights(pretrained=None)
# cpu
input_shape = (1, 3, 64, 64)
img = _demo_inputs(input_shape)
output = net(img)
assert output.shape == (1, 1, 6, 6)
# gpu
if torch.cuda.is_available():
net.init_weights(pretrained=None)
net = net.cuda()
output = net(img.cuda())
assert output.shape == (1, 1, 6, 6)
# pretrained should be str or None
with pytest.raises(TypeError):
net.init_weights(pretrained=[1])
# gray, IN
cfg = dict(
type='SoftMaskPatchDiscriminator',
in_channels=1,
base_channels=64,
num_conv=3,
with_spectral_norm=True)
net = build_component(cfg)
net.init_weights(pretrained=None)
# cpu
input_shape = (1, 1, 64, 64)
img = _demo_inputs(input_shape)
output = net(img)
assert output.shape == (1, 1, 6, 6)
# gpu
if torch.cuda.is_available():
net.init_weights(pretrained=None)
net = net.cuda()
output = net(img.cuda())
assert output.shape == (1, 1, 6, 6)
# pretrained should be str or None
with pytest.raises(TypeError):
net.init_weights(pretrained=[1])
def _demo_inputs(input_shape=(1, 3, 64, 64)):
"""Create a superset of inputs needed to run backbone.
Args:
input_shape (tuple): input batch dimensions.
Default: (1, 3, 64, 64).
Returns:
imgs: (Tensor): Images in FloatTensor with desired shapes.
"""
imgs = np.random.random(input_shape)
imgs = torch.FloatTensor(imgs)
return imgs
| 4,322 | 26.01875 | 68 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_components/test_discriminators/test_deepfill_disc.py | # Copyright (c) OpenMMLab. All rights reserved.
import pytest
import torch
from mmedit.models.components import (DeepFillv1Discriminators,
MultiLayerDiscriminator)
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=dict(
type='MultiLayerDiscriminator',
in_channels=3,
max_channels=512,
fc_in_channels=512 * 8 * 8,
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)))
disc = DeepFillv1Discriminators(**model_config)
disc.init_weights()
global_x = torch.rand((2, 3, 256, 256))
local_x = torch.rand((2, 3, 128, 128))
global_pred, local_pred = disc((global_x, local_x))
assert global_pred.shape == (2, 1)
assert local_pred.shape == (2, 1)
assert isinstance(disc.global_disc, MultiLayerDiscriminator)
assert isinstance(disc.local_disc, MultiLayerDiscriminator)
with pytest.raises(TypeError):
disc.init_weights(model_config)
if torch.cuda.is_available():
disc = DeepFillv1Discriminators(**model_config).cuda()
disc.init_weights()
global_x = torch.rand((2, 3, 256, 256)).cuda()
local_x = torch.rand((2, 3, 128, 128)).cuda()
global_pred, local_pred = disc((global_x, local_x))
assert global_pred.shape == (2, 1)
assert local_pred.shape == (2, 1)
| 1,862 | 34.826923 | 68 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_components/test_discriminators/test_multi_layer_disc.py | # Copyright (c) OpenMMLab. All rights reserved.
import pytest
import torch
import torch.nn as nn
from mmedit.models.components import MultiLayerDiscriminator
def test_multi_layer_disc():
with pytest.raises(AssertionError):
# fc_in_channels must be greater than 0
multi_disc = MultiLayerDiscriminator(
3, 236, fc_in_channels=-100, out_act_cfg=None)
with pytest.raises(TypeError):
# stride_list must be a tuple of int with length of 1 or
# length of num_conv
multi_disc = MultiLayerDiscriminator(
3, 256, num_convs=3, stride_list=(1, 2))
input_g = torch.randn(1, 3, 256, 256)
# test multi-layer discriminators without fc layer
multi_disc = MultiLayerDiscriminator(
in_channels=3, max_channels=256, fc_in_channels=None)
multi_disc.init_weights()
disc_pred = multi_disc(input_g)
assert disc_pred.shape == (1, 256, 8, 8)
multi_disc = MultiLayerDiscriminator(
in_channels=3, max_channels=256, fc_in_channels=100)
assert isinstance(multi_disc.fc.activate, nn.ReLU)
multi_disc = MultiLayerDiscriminator(3, 236, fc_in_channels=None)
assert multi_disc.with_out_act
assert not multi_disc.with_fc
assert isinstance(multi_disc.conv5.activate, nn.ReLU)
multi_disc = MultiLayerDiscriminator(
3, 236, fc_in_channels=None, out_act_cfg=None)
assert not multi_disc.conv5.with_activation
with pytest.raises(TypeError):
multi_disc.init_weights(pretrained=dict(igccc=4396))
input_g = torch.randn(1, 3, 16, 16)
multi_disc = MultiLayerDiscriminator(
in_channels=3,
max_channels=256,
num_convs=2,
fc_in_channels=4 * 4 * 128,
fc_out_channels=10,
with_spectral_norm=True)
multi_disc.init_weights()
disc_pred = multi_disc(input_g)
assert disc_pred.shape == (1, 10)
assert multi_disc.conv1.with_spectral_norm
assert multi_disc.conv2.with_spectral_norm
assert hasattr(multi_disc.fc.linear, 'weight_orig')
num_convs = 3
multi_disc = MultiLayerDiscriminator(
in_channels=64,
max_channels=512,
num_convs=num_convs,
kernel_size=4,
norm_cfg=dict(type='BN'),
act_cfg=dict(type='LeakyReLU', negative_slope=0.2),
out_act_cfg=dict(type='ReLU'),
with_input_norm=False,
with_out_convs=True)
# check input conv
assert not multi_disc.conv1.with_norm
assert isinstance(multi_disc.conv1.activate, nn.LeakyReLU)
assert multi_disc.conv1.stride == (2, 2)
# check intermediate conv
for i in range(1, num_convs):
assert getattr(multi_disc, f'conv{i + 1}').with_norm
assert isinstance(
getattr(multi_disc, f'conv{i + 1}').activate, nn.LeakyReLU)
assert getattr(multi_disc, f'conv{i + 1}').stride == (2, 2)
# check out_conv
assert multi_disc.conv4.with_norm
assert multi_disc.conv4.with_activation
assert multi_disc.conv4.stride == (1, 1)
assert not multi_disc.conv5.with_norm
assert not multi_disc.conv5.with_activation
assert multi_disc.conv5.stride == (1, 1)
| 3,133 | 34.613636 | 71 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_inpaintors/test_deepfill_inpaintor.py | # Copyright (c) OpenMMLab. All rights reserved.
import copy
import os
import tempfile
import pytest
import torch
from mmcv import Config
from mmedit.core import build_optimizers
from mmedit.models import DeepFillv1Inpaintor
def test_two_stage_inpaintor():
model = dict(
disc_input_with_mask=True,
encdec=dict(type='DeepFillEncoderDecoder'),
disc=dict(
type='DeepFillv1Discriminators',
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=dict(
type='MultiLayerDiscriminator',
in_channels=3,
max_channels=512,
fc_in_channels=512 * 8 * 8,
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))),
stage1_loss_type=('loss_l1_hole', 'loss_l1_valid'),
stage2_loss_type=('loss_l1_hole', 'loss_l1_valid', 'loss_gan'),
loss_gan=dict(
type='GANLoss',
gan_type='hinge',
loss_weight=1,
),
loss_l1_hole=dict(
type='L1Loss',
loss_weight=1.0,
),
loss_l1_valid=dict(
type='L1Loss',
loss_weight=1.0,
),
pretrained=None)
train_cfg = Config(dict(disc_step=1, local_size=(128, 128)))
test_cfg = Config(dict(metrics=['l1']))
tsinpaintor = DeepFillv1Inpaintor(
**model, train_cfg=train_cfg, test_cfg=test_cfg)
# check architecture
assert tsinpaintor.stage1_loss_type == ('loss_l1_hole', 'loss_l1_valid')
assert tsinpaintor.stage2_loss_type == ('loss_l1_hole', 'loss_l1_valid',
'loss_gan')
assert tsinpaintor.with_l1_hole_loss
assert tsinpaintor.with_l1_valid_loss
assert not tsinpaintor.with_composed_percep_loss
assert not tsinpaintor.with_out_percep_loss
assert tsinpaintor.with_gan
if torch.cuda.is_available():
# prepare data
gt_img = torch.rand((2, 3, 256, 256)).cuda()
mask = torch.zeros((2, 1, 256, 256)).cuda()
mask[..., 50:180, 60:170] = 1.
masked_img = gt_img * (1. - mask)
bbox_tensor = torch.tensor([[50, 60, 110, 110], [50, 60, 110,
110]]).cuda()
data_batch = dict(
gt_img=gt_img,
mask=mask,
masked_img=masked_img,
mask_bbox=bbox_tensor)
# prepare model and optimizer
tsinpaintor.cuda()
optimizers_config = dict(
generator=dict(type='Adam', lr=0.0001),
disc=dict(type='Adam', lr=0.0001))
optims = build_optimizers(tsinpaintor, optimizers_config)
# check train_step with standard deepfillv2 model
outputs = tsinpaintor.train_step(data_batch, optims)
assert outputs['num_samples'] == 2
log_vars = outputs['log_vars']
assert 'real_loss_global' in log_vars
assert 'stage1_loss_l1_hole' in log_vars
assert 'stage1_loss_l1_valid' in log_vars
assert 'stage2_loss_l1_hole' in log_vars
assert 'stage2_loss_l1_valid' in log_vars
assert 'stage1_fake_res' in outputs['results']
assert 'stage2_fake_res' in outputs['results']
assert outputs['results']['stage1_fake_res'].size() == (2, 3, 256, 256)
# check train step w/o disc step
tsinpaintor.train_cfg.disc_step = 0
outputs = tsinpaintor.train_step(data_batch, optims)
assert outputs['num_samples'] == 2
log_vars = outputs['log_vars']
assert 'real_loss_global' not in log_vars
assert 'stage1_loss_l1_hole' in log_vars
assert 'stage1_loss_l1_valid' in log_vars
assert 'stage2_loss_l1_hole' in log_vars
assert 'stage2_loss_l1_valid' in log_vars
assert 'stage1_fake_res' in outputs['results']
assert 'stage2_fake_res' in outputs['results']
assert outputs['results']['stage1_fake_res'].size() == (2, 3, 256, 256)
tsinpaintor.train_cfg.disc_step = 1
# check train step w/ multiple disc step
tsinpaintor.train_cfg.disc_step = 5
outputs = tsinpaintor.train_step(data_batch, optims)
assert outputs['num_samples'] == 2
log_vars = outputs['log_vars']
assert 'real_loss_global' in log_vars
assert 'stage1_loss_l1_hole' not in log_vars
assert outputs['results']['fake_res'].size() == (2, 3, 256, 256)
tsinpaintor.train_cfg.disc_step = 1
# test forward test w/o save image
outputs = tsinpaintor.forward_test(
masked_img[0:1], mask[0:1], gt_img=gt_img[0:1, ...])
assert 'eval_result' in outputs
assert outputs['eval_result']['l1'] > 0
# test forward test w/o eval metrics
tsinpaintor.test_cfg = dict()
tsinpaintor.eval_with_metrics = False
outputs = tsinpaintor.forward_test(masked_img[0:1], mask[0:1])
for key in [
'stage1_fake_res', 'stage2_fake_res', 'fake_res', 'fake_img'
]:
assert outputs[key].size() == (1, 3, 256, 256)
# test forward test w/ save image
with tempfile.TemporaryDirectory() as tmpdir:
outputs = tsinpaintor.forward_test(
masked_img[0:1],
mask[0:1],
save_image=True,
save_path=tmpdir,
iteration=4396,
meta=[dict(gt_img_path='igccc.png')])
assert os.path.exists(os.path.join(tmpdir, 'igccc_4396.png'))
# test forward test w/ save image w/ gt_img
with tempfile.TemporaryDirectory() as tmpdir:
outputs = tsinpaintor.forward_test(
masked_img[0:1],
mask[0:1],
save_image=True,
save_path=tmpdir,
meta=[dict(gt_img_path='igccc.png')],
gt_img=gt_img[0:1, ...])
assert os.path.exists(os.path.join(tmpdir, 'igccc.png'))
with pytest.raises(AssertionError):
outputs = tsinpaintor.forward_test(
masked_img[0:1],
mask[0:1],
save_image=True,
save_path=tmpdir,
iteration=4396,
gt_img=gt_img[0:1, ...])
with pytest.raises(AssertionError):
outputs = tsinpaintor.forward_test(
masked_img[0:1],
mask[0:1],
save_image=True,
save_path=None,
iteration=4396,
meta=[dict(gt_img_path='igccc.png')],
gt_img=gt_img[0:1, ...])
# check train_step with not implemented loss type
with pytest.raises(NotImplementedError):
model_ = copy.deepcopy(model)
model_['stage1_loss_type'] = ('igccc', )
tsinpaintor = DeepFillv1Inpaintor(
**model_, train_cfg=train_cfg, test_cfg=test_cfg).cuda()
outputs = tsinpaintor.train_step(data_batch, optims)
# test input w/o ones and disc input w/o mask
model_ = dict(
disc_input_with_mask=False,
input_with_ones=False,
encdec=dict(
type='DeepFillEncoderDecoder',
stage1=dict(
type='GLEncoderDecoder',
encoder=dict(type='DeepFillEncoder', in_channels=4),
decoder=dict(type='DeepFillDecoder', in_channels=128),
dilation_neck=dict(
type='GLDilationNeck',
in_channels=128,
act_cfg=dict(type='ELU'))),
stage2=dict(
type='DeepFillRefiner',
encoder_attention=dict(
type='DeepFillEncoder',
encoder_type='stage2_attention',
in_channels=4),
encoder_conv=dict(
type='DeepFillEncoder',
encoder_type='stage2_conv',
in_channels=4)),
),
disc=dict(
type='DeepFillv1Discriminators',
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=dict(
type='MultiLayerDiscriminator',
in_channels=3,
max_channels=512,
fc_in_channels=512 * 8 * 8,
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))),
stage1_loss_type=('loss_l1_hole', 'loss_l1_valid'),
stage2_loss_type=('loss_l1_hole', 'loss_l1_valid', 'loss_gan'),
loss_gan=dict(
type='GANLoss',
gan_type='hinge',
loss_weight=1,
),
loss_l1_hole=dict(
type='L1Loss',
loss_weight=1.0,
),
loss_gp=dict(type='GradientPenaltyLoss', loss_weight=10.),
loss_tv=dict(
type='MaskedTVLoss',
loss_weight=0.1,
),
loss_l1_valid=dict(
type='L1Loss',
loss_weight=1.0,
),
loss_disc_shift=dict(type='DiscShiftLoss'),
pretrained=None)
tsinpaintor = DeepFillv1Inpaintor(
**model_, train_cfg=train_cfg, test_cfg=test_cfg).cuda()
outputs = tsinpaintor.train_step(data_batch, optims)
assert outputs['num_samples'] == 2
log_vars = outputs['log_vars']
assert 'real_loss_global' in log_vars
assert 'stage1_loss_l1_hole' in log_vars
assert 'stage1_loss_l1_valid' in log_vars
assert 'stage2_loss_l1_hole' in log_vars
assert 'stage2_loss_l1_valid' in log_vars
assert 'stage1_fake_res' in outputs['results']
assert 'stage2_fake_res' in outputs['results']
assert outputs['results']['stage1_fake_res'].size() == (2, 3, 256, 256)
outputs = tsinpaintor.forward_test(
masked_img[0:1], mask[0:1], gt_img=gt_img[0:1, ...])
assert 'eval_result' in outputs
assert outputs['eval_result']['l1'] > 0
# test w/o stage1 loss
model_ = copy.deepcopy(model)
model_['stage1_loss_type'] = None
tsinpaintor = DeepFillv1Inpaintor(
**model_, train_cfg=train_cfg, test_cfg=test_cfg).cuda()
outputs = tsinpaintor.train_step(data_batch, optims)
assert outputs['num_samples'] == 2
log_vars = outputs['log_vars']
assert 'real_loss_global' in log_vars
assert 'stage1_loss_l1_hole' not in log_vars
assert 'stage1_loss_l1_valid' not in log_vars
assert 'stage2_loss_l1_hole' in log_vars
assert 'stage2_loss_l1_valid' in log_vars
assert 'stage1_fake_res' in outputs['results']
assert 'stage2_fake_res' in outputs['results']
assert outputs['results']['stage1_fake_res'].size() == (2, 3, 256, 256)
# test w/o stage2 loss
model_ = copy.deepcopy(model)
model_['stage2_loss_type'] = None
tsinpaintor = DeepFillv1Inpaintor(
**model_, train_cfg=train_cfg, test_cfg=test_cfg).cuda()
outputs = tsinpaintor.train_step(data_batch, optims)
assert outputs['num_samples'] == 2
log_vars = outputs['log_vars']
assert 'real_loss_global' in log_vars
assert 'stage1_loss_l1_hole' in log_vars
assert 'stage1_loss_l1_valid' in log_vars
assert 'stage2_loss_l1_hole' not in log_vars
assert 'stage2_loss_l1_valid' not in log_vars
assert 'stage1_fake_res' in outputs['results']
assert 'stage2_fake_res' in outputs['results']
assert outputs['results']['stage1_fake_res'].size() == (2, 3, 256, 256)
| 12,857 | 38.441718 | 79 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_inpaintors/test_gl_inpaintor.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch
from mmcv import Config
from mmedit.models import build_model
def test_gl_inpaintor():
cfg = Config.fromfile('tests/data/inpaintor_config/gl_test.py')
gl = build_model(cfg.model, train_cfg=cfg.train_cfg, test_cfg=cfg.test_cfg)
assert gl.__class__.__name__ == 'GLInpaintor'
if torch.cuda.is_available():
gt_img = torch.randn(1, 3, 256, 256)
mask = torch.zeros_like(gt_img)[:, 0:1, ...]
mask[..., 100:210, 100:210] = 1.
masked_img = gt_img * (1. - mask)
mask_bbox = torch.tensor([[100, 100, 110, 110]])
gl.cuda()
data_batch = dict(
gt_img=gt_img.cuda(),
mask=mask.cuda(),
masked_img=masked_img.cuda(),
mask_bbox=mask_bbox.cuda())
optim_g = torch.optim.SGD(gl.generator.parameters(), lr=0.1)
optim_d = torch.optim.SGD(gl.disc.parameters(), lr=0.1)
optim_dict = dict(generator=optim_g, disc=optim_d)
for i in range(5):
outputs = gl.train_step(data_batch, optim_dict)
if i <= 2:
assert 'loss_l1_hole' in outputs['log_vars']
assert 'fake_loss' not in outputs['log_vars']
assert 'real_loss' not in outputs['log_vars']
assert 'loss_g_fake' not in outputs['log_vars']
elif i == 3:
assert 'loss_l1_hole' not in outputs['log_vars']
assert 'fake_loss' in outputs['log_vars']
assert 'real_loss' in outputs['log_vars']
assert 'loss_g_fake' not in outputs['log_vars']
else:
assert 'loss_l1_hole' in outputs['log_vars']
assert 'fake_loss' in outputs['log_vars']
assert 'real_loss' in outputs['log_vars']
assert 'loss_g_fake' in outputs['log_vars']
gl_dirty = build_model(
cfg.model_dirty, train_cfg=cfg.train_cfg, test_cfg=cfg.test_cfg)
gl_dirty.cuda()
res, loss = gl_dirty.generator_loss(gt_img, gt_img, gt_img, data_batch)
assert len(loss) == 0
| 2,138 | 37.196429 | 79 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_inpaintors/test_pconv_inpaintor.py | # Copyright (c) OpenMMLab. All rights reserved.
import os
import tempfile
from unittest.mock import patch
import pytest
import torch
from mmcv import Config
from mmedit.models import build_model
from mmedit.models.losses import PerceptualVGG
@patch.object(PerceptualVGG, 'init_weights')
def test_pconv_inpaintor(init_weights):
cfg = Config.fromfile(
'tests/data/inpaintor_config/pconv_inpaintor_test.py')
if torch.cuda.is_available():
pconv_inpaintor = build_model(
cfg.model, train_cfg=cfg.train_cfg, test_cfg=cfg.test_cfg)
assert pconv_inpaintor.__class__.__name__ == 'PConvInpaintor'
pconv_inpaintor.cuda()
gt_img = torch.randn((1, 3, 256, 256)).cuda()
mask = torch.zeros_like(gt_img)
mask[..., 50:160, 100:210] = 1.
masked_img = gt_img * (1. - mask)
data_batch = dict(gt_img=gt_img, mask=mask, masked_img=masked_img)
optim_g = torch.optim.SGD(
pconv_inpaintor.generator.parameters(), lr=0.1)
optim_dict = dict(generator=optim_g)
outputs = pconv_inpaintor.train_step(data_batch, optim_dict)
assert outputs['results']['fake_res'].shape == (1, 3, 256, 256)
assert outputs['results']['final_mask'].shape == (1, 3, 256, 256)
assert 'loss_l1_hole' in outputs['log_vars']
assert 'loss_l1_valid' in outputs['log_vars']
assert 'loss_tv' in outputs['log_vars']
# test forward dummy
res = pconv_inpaintor.forward_dummy(
torch.cat([masked_img, mask], dim=1))
assert res.shape == (1, 3, 256, 256)
# test forward test w/o save image
outputs = pconv_inpaintor.forward_test(
masked_img[0:1], mask[0:1], gt_img=gt_img[0:1, ...])
assert 'eval_result' in outputs
assert outputs['eval_result']['l1'] > 0
assert outputs['eval_result']['psnr'] > 0
assert outputs['eval_result']['ssim'] > 0
# test forward test w/o eval metrics
pconv_inpaintor.test_cfg = dict()
pconv_inpaintor.eval_with_metrics = False
outputs = pconv_inpaintor.forward_test(masked_img[0:1], mask[0:1])
for key in ['fake_res', 'fake_img']:
assert outputs[key].size() == (1, 3, 256, 256)
# test forward test w/ save image
with tempfile.TemporaryDirectory() as tmpdir:
outputs = pconv_inpaintor.forward_test(
masked_img[0:1],
mask[0:1],
save_image=True,
save_path=tmpdir,
iteration=4396,
meta=[dict(gt_img_path='igccc.png')])
assert os.path.exists(os.path.join(tmpdir, 'igccc_4396.png'))
# test forward test w/ save image w/ gt_img
with tempfile.TemporaryDirectory() as tmpdir:
outputs = pconv_inpaintor.forward_test(
masked_img[0:1],
mask[0:1],
save_image=True,
save_path=tmpdir,
meta=[dict(gt_img_path='igccc.png')],
gt_img=gt_img[0:1, ...])
assert os.path.exists(os.path.join(tmpdir, 'igccc.png'))
with pytest.raises(AssertionError):
outputs = pconv_inpaintor.forward_test(
masked_img[0:1],
mask[0:1],
save_image=True,
save_path=tmpdir,
iteration=4396,
gt_img=gt_img[0:1, ...])
with pytest.raises(AssertionError):
outputs = pconv_inpaintor.forward_test(
masked_img[0:1],
mask[0:1],
save_image=True,
save_path=None,
iteration=4396,
meta=[dict(gt_img_path='igccc.png')],
gt_img=gt_img[0:1, ...])
# reset mock to clear some memory usage
init_weights.reset_mock()
| 3,937 | 36.865385 | 74 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_inpaintors/test_two_stage_inpaintor.py | # Copyright (c) OpenMMLab. All rights reserved.
import copy
import os
import tempfile
import pytest
import torch
from mmcv import Config
from mmedit.core import build_optimizers
from mmedit.models import TwoStageInpaintor
def test_two_stage_inpaintor():
model = dict(
disc_input_with_mask=True,
encdec=dict(
type='DeepFillEncoderDecoder',
stage1=dict(
type='GLEncoderDecoder',
encoder=dict(
type='DeepFillEncoder',
conv_type='gated_conv',
channel_factor=0.75),
decoder=dict(
type='DeepFillDecoder',
conv_type='gated_conv',
in_channels=96,
channel_factor=0.75),
dilation_neck=dict(
type='GLDilationNeck',
in_channels=96,
conv_type='gated_conv',
act_cfg=dict(type='ELU'))),
stage2=dict(
type='DeepFillRefiner',
encoder_attention=dict(
type='DeepFillEncoder',
encoder_type='stage2_attention',
conv_type='gated_conv',
channel_factor=0.75),
encoder_conv=dict(
type='DeepFillEncoder',
encoder_type='stage2_conv',
conv_type='gated_conv',
channel_factor=0.75),
dilation_neck=dict(
type='GLDilationNeck',
in_channels=96,
conv_type='gated_conv',
act_cfg=dict(type='ELU')),
contextual_attention=dict(
type='ContextualAttentionNeck',
in_channels=96,
conv_type='gated_conv'),
decoder=dict(
type='DeepFillDecoder',
in_channels=192,
conv_type='gated_conv'))),
disc=dict(
type='MultiLayerDiscriminator',
in_channels=4,
max_channels=256,
fc_in_channels=256 * 4 * 4,
fc_out_channels=1,
num_convs=6,
norm_cfg=None,
act_cfg=dict(type='ELU'),
out_act_cfg=dict(type='LeakyReLU', negative_slope=0.2),
with_spectral_norm=True,
),
stage1_loss_type=('loss_l1_hole', 'loss_l1_valid'),
stage2_loss_type=('loss_l1_hole', 'loss_l1_valid', 'loss_gan'),
loss_gan=dict(
type='GANLoss',
gan_type='hinge',
loss_weight=1,
),
loss_l1_hole=dict(
type='L1Loss',
loss_weight=1.0,
),
loss_l1_valid=dict(
type='L1Loss',
loss_weight=1.0,
),
pretrained=None)
train_cfg = Config(dict(disc_step=1))
test_cfg = Config(dict(metrics=['l1', 'psnr', 'ssim']))
tsinpaintor = TwoStageInpaintor(
**model, train_cfg=train_cfg, test_cfg=test_cfg)
# check architecture
assert tsinpaintor.stage1_loss_type == ('loss_l1_hole', 'loss_l1_valid')
assert tsinpaintor.stage2_loss_type == ('loss_l1_hole', 'loss_l1_valid',
'loss_gan')
assert tsinpaintor.with_l1_hole_loss
assert tsinpaintor.with_l1_valid_loss
assert not tsinpaintor.with_composed_percep_loss
assert not tsinpaintor.with_out_percep_loss
assert tsinpaintor.with_gan
if torch.cuda.is_available():
# prepare data
gt_img = torch.rand((2, 3, 256, 256)).cuda()
mask = torch.zeros((2, 1, 256, 256)).cuda()
mask[..., 50:180, 60:170] = 1.
masked_img = gt_img * (1. - mask)
data_batch = dict(gt_img=gt_img, mask=mask, masked_img=masked_img)
# prepare model and optimizer
tsinpaintor.cuda()
optimizers_config = dict(
generator=dict(type='Adam', lr=0.0001),
disc=dict(type='Adam', lr=0.0001))
optims = build_optimizers(tsinpaintor, optimizers_config)
# check train_step with standard deepfillv2 model
outputs = tsinpaintor.train_step(data_batch, optims)
assert outputs['num_samples'] == 2
log_vars = outputs['log_vars']
assert 'real_loss' in log_vars
assert 'stage1_loss_l1_hole' in log_vars
assert 'stage1_loss_l1_valid' in log_vars
assert 'stage2_loss_l1_hole' in log_vars
assert 'stage2_loss_l1_valid' in log_vars
assert 'stage1_fake_res' in outputs['results']
assert 'stage2_fake_res' in outputs['results']
assert outputs['results']['stage1_fake_res'].size() == (2, 3, 256, 256)
# check train step w/o disc step
tsinpaintor.train_cfg.disc_step = 0
outputs = tsinpaintor.train_step(data_batch, optims)
assert outputs['num_samples'] == 2
log_vars = outputs['log_vars']
assert 'real_loss' not in log_vars
assert 'stage1_loss_l1_hole' in log_vars
assert 'stage1_loss_l1_valid' in log_vars
assert 'stage2_loss_l1_hole' in log_vars
assert 'stage2_loss_l1_valid' in log_vars
assert 'stage1_fake_res' in outputs['results']
assert 'stage2_fake_res' in outputs['results']
assert outputs['results']['stage1_fake_res'].size() == (2, 3, 256, 256)
tsinpaintor.train_cfg.disc_step = 1
# check train step w/ multiple disc step
tsinpaintor.train_cfg.disc_step = 5
outputs = tsinpaintor.train_step(data_batch, optims)
assert outputs['num_samples'] == 2
log_vars = outputs['log_vars']
assert 'real_loss' in log_vars
assert 'stage1_loss_l1_hole' not in log_vars
assert outputs['results']['fake_res'].size() == (2, 3, 256, 256)
tsinpaintor.train_cfg.disc_step = 1
# test forward test w/o save image
outputs = tsinpaintor.forward_test(
masked_img[0:1], mask[0:1], gt_img=gt_img[0:1, ...])
assert 'eval_result' in outputs
assert outputs['eval_result']['l1'] > 0
assert outputs['eval_result']['psnr'] > 0
assert outputs['eval_result']['ssim'] > 0
# test forward test w/o eval metrics
tsinpaintor.test_cfg = dict()
tsinpaintor.eval_with_metrics = False
outputs = tsinpaintor.forward_test(masked_img[0:1], mask[0:1])
for key in [
'stage1_fake_res', 'stage2_fake_res', 'fake_res', 'fake_img'
]:
assert outputs[key].size() == (1, 3, 256, 256)
# test forward test w/ save image
with tempfile.TemporaryDirectory() as tmpdir:
outputs = tsinpaintor.forward_test(
masked_img[0:1],
mask[0:1],
save_image=True,
save_path=tmpdir,
iteration=4396,
meta=[dict(gt_img_path='igccc.png')])
assert os.path.exists(os.path.join(tmpdir, 'igccc_4396.png'))
# test forward test w/ save image w/ gt_img
with tempfile.TemporaryDirectory() as tmpdir:
outputs = tsinpaintor.forward_test(
masked_img[0:1],
mask[0:1],
save_image=True,
save_path=tmpdir,
meta=[dict(gt_img_path='igccc.png')],
gt_img=gt_img[0:1, ...])
assert os.path.exists(os.path.join(tmpdir, 'igccc.png'))
with pytest.raises(AssertionError):
outputs = tsinpaintor.forward_test(
masked_img[0:1],
mask[0:1],
save_image=True,
save_path=tmpdir,
iteration=4396,
gt_img=gt_img[0:1, ...])
with pytest.raises(AssertionError):
outputs = tsinpaintor.forward_test(
masked_img[0:1],
mask[0:1],
save_image=True,
save_path=None,
iteration=4396,
meta=[dict(gt_img_path='igccc.png')],
gt_img=gt_img[0:1, ...])
# check train_step with not implemented loss type
with pytest.raises(NotImplementedError):
model_ = copy.deepcopy(model)
model_['stage1_loss_type'] = ('igccc', )
tsinpaintor = TwoStageInpaintor(
**model_, train_cfg=train_cfg, test_cfg=test_cfg).cuda()
outputs = tsinpaintor.train_step(data_batch, optims)
# test input w/o ones and disc input w/o mask
model_ = dict(
disc_input_with_mask=False,
input_with_ones=False,
encdec=dict(
type='DeepFillEncoderDecoder',
stage1=dict(
type='GLEncoderDecoder',
encoder=dict(
type='DeepFillEncoder',
in_channels=4,
conv_type='gated_conv',
channel_factor=0.75),
decoder=dict(
type='DeepFillDecoder',
conv_type='gated_conv',
in_channels=96,
channel_factor=0.75),
dilation_neck=dict(
type='GLDilationNeck',
in_channels=96,
conv_type='gated_conv',
act_cfg=dict(type='ELU'))),
stage2=dict(
type='DeepFillRefiner',
encoder_attention=dict(
type='DeepFillEncoder',
in_channels=4,
encoder_type='stage2_attention',
conv_type='gated_conv',
channel_factor=0.75),
encoder_conv=dict(
type='DeepFillEncoder',
in_channels=4,
encoder_type='stage2_conv',
conv_type='gated_conv',
channel_factor=0.75),
dilation_neck=dict(
type='GLDilationNeck',
in_channels=96,
conv_type='gated_conv',
act_cfg=dict(type='ELU')),
contextual_attention=dict(
type='ContextualAttentionNeck',
in_channels=96,
conv_type='gated_conv'),
decoder=dict(
type='DeepFillDecoder',
in_channels=192,
conv_type='gated_conv'))),
disc=dict(
type='MultiLayerDiscriminator',
in_channels=3,
max_channels=256,
fc_in_channels=256 * 4 * 4,
fc_out_channels=1,
num_convs=6,
norm_cfg=None,
act_cfg=dict(type='ELU'),
out_act_cfg=dict(type='LeakyReLU', negative_slope=0.2),
with_spectral_norm=True,
),
stage1_loss_type=('loss_l1_hole', 'loss_l1_valid'),
stage2_loss_type=('loss_l1_hole', 'loss_l1_valid', 'loss_gan'),
loss_gan=dict(
type='GANLoss',
gan_type='hinge',
loss_weight=1,
),
loss_l1_hole=dict(
type='L1Loss',
loss_weight=1.0,
),
loss_gp=dict(type='GradientPenaltyLoss', loss_weight=10.),
loss_tv=dict(
type='MaskedTVLoss',
loss_weight=0.1,
),
loss_l1_valid=dict(
type='L1Loss',
loss_weight=1.0,
),
pretrained=None)
tsinpaintor = TwoStageInpaintor(
**model_, train_cfg=train_cfg, test_cfg=test_cfg).cuda()
outputs = tsinpaintor.train_step(data_batch, optims)
assert outputs['num_samples'] == 2
log_vars = outputs['log_vars']
assert 'real_loss' in log_vars
assert 'stage1_loss_l1_hole' in log_vars
assert 'stage1_loss_l1_valid' in log_vars
assert 'stage2_loss_l1_hole' in log_vars
assert 'stage2_loss_l1_valid' in log_vars
assert 'stage1_fake_res' in outputs['results']
assert 'stage2_fake_res' in outputs['results']
assert outputs['results']['stage1_fake_res'].size() == (2, 3, 256, 256)
outputs = tsinpaintor.forward_test(
masked_img[0:1], mask[0:1], gt_img=gt_img[0:1, ...])
assert 'eval_result' in outputs
assert outputs['eval_result']['l1'] > 0
# test w/o stage1 loss
model_ = copy.deepcopy(model)
model_['stage1_loss_type'] = None
tsinpaintor = TwoStageInpaintor(
**model_, train_cfg=train_cfg, test_cfg=test_cfg).cuda()
outputs = tsinpaintor.train_step(data_batch, optims)
assert outputs['num_samples'] == 2
log_vars = outputs['log_vars']
assert 'real_loss' in log_vars
assert 'stage1_loss_l1_hole' not in log_vars
assert 'stage1_loss_l1_valid' not in log_vars
assert 'stage2_loss_l1_hole' in log_vars
assert 'stage2_loss_l1_valid' in log_vars
assert 'stage1_fake_res' in outputs['results']
assert 'stage2_fake_res' in outputs['results']
assert outputs['results']['stage1_fake_res'].size() == (2, 3, 256, 256)
# test w/o stage2 loss
model_ = copy.deepcopy(model)
model_['stage2_loss_type'] = None
tsinpaintor = TwoStageInpaintor(
**model_, train_cfg=train_cfg, test_cfg=test_cfg).cuda()
outputs = tsinpaintor.train_step(data_batch, optims)
assert outputs['num_samples'] == 2
log_vars = outputs['log_vars']
assert 'real_loss' in log_vars
assert 'stage1_loss_l1_hole' in log_vars
assert 'stage1_loss_l1_valid' in log_vars
assert 'stage2_loss_l1_hole' not in log_vars
assert 'stage2_loss_l1_valid' not in log_vars
assert 'stage1_fake_res' in outputs['results']
assert 'stage2_fake_res' in outputs['results']
assert outputs['results']['stage1_fake_res'].size() == (2, 3, 256, 256)
| 14,419 | 38.184783 | 79 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_inpaintors/test_one_stage_inpaintor.py | # Copyright (c) OpenMMLab. All rights reserved.
import copy
import os
import tempfile
from unittest.mock import patch
import pytest
import torch
from mmcv import Config
from mmedit.models import build_model
from mmedit.models.backbones import GLEncoderDecoder
def test_one_stage_inpaintor():
cfg = Config.fromfile('tests/data/inpaintor_config/one_stage_gl.py')
# mock perceptual loss for test speed
cfg.model.loss_composed_percep = None
inpaintor = build_model(
cfg.model, train_cfg=cfg.train_cfg, test_cfg=cfg.test_cfg)
# modify attributes for mocking
inpaintor.with_composed_percep_loss = True
inpaintor.loss_percep = None
# test attributes
assert inpaintor.__class__.__name__ == 'OneStageInpaintor'
assert isinstance(inpaintor.generator, GLEncoderDecoder)
assert inpaintor.with_l1_hole_loss
assert inpaintor.with_l1_valid_loss
assert inpaintor.with_tv_loss
assert inpaintor.with_composed_percep_loss
assert inpaintor.with_out_percep_loss
assert inpaintor.with_gan
assert inpaintor.with_gp_loss
assert inpaintor.with_disc_shift_loss
assert inpaintor.is_train
assert inpaintor.train_cfg['disc_step'] == 1
assert inpaintor.disc_step_count == 0
with patch.object(
inpaintor, 'loss_percep', return_value=(torch.tensor(1.0), None)):
input_x = torch.randn(1, 3, 256, 256)
with pytest.raises(NotImplementedError):
inpaintor.forward_train(input_x)
if torch.cuda.is_available():
gt_img = torch.randn(1, 3, 256, 256).cuda()
mask = torch.zeros_like(gt_img)[:, 0:1, ...]
mask[..., 20:100, 100:120] = 1.
masked_img = gt_img * (1. - mask)
inpaintor.cuda()
data_batch = dict(gt_img=gt_img, mask=mask, masked_img=masked_img)
output = inpaintor.forward_test(**data_batch)
assert 'eval_result' in output
output = inpaintor.val_step(data_batch)
assert 'eval_result' in output
optim_g = torch.optim.SGD(inpaintor.generator.parameters(), lr=0.1)
optim_d = torch.optim.SGD(inpaintor.disc.parameters(), lr=0.1)
optim_dict = dict(generator=optim_g, disc=optim_d)
outputs = inpaintor.train_step(data_batch, optim_dict)
assert outputs['num_samples'] == 1
results = outputs['results']
assert results['fake_res'].shape == (1, 3, 256, 256)
assert 'loss_l1_hole' in outputs['log_vars']
assert 'loss_l1_valid' in outputs['log_vars']
assert 'loss_composed_percep' in outputs['log_vars']
assert 'loss_composed_style' not in outputs['log_vars']
assert 'loss_out_percep' in outputs['log_vars']
assert 'loss_out_style' not in outputs['log_vars']
assert 'loss_tv' in outputs['log_vars']
assert 'fake_loss' in outputs['log_vars']
assert 'real_loss' in outputs['log_vars']
assert 'loss_g_fake' in outputs['log_vars']
# test forward dummy
res = inpaintor.forward_dummy(torch.cat([masked_img, mask], dim=1))
assert res.shape == (1, 3, 256, 256)
# test forward test w/o save image
outputs = inpaintor.forward_test(
masked_img[0:1], mask[0:1], gt_img=gt_img[0:1, ...])
assert 'eval_result' in outputs
assert outputs['eval_result']['l1'] > 0
assert outputs['eval_result']['psnr'] > 0
assert outputs['eval_result']['ssim'] > 0
# test forward test w/o eval metrics
inpaintor.test_cfg = dict()
inpaintor.eval_with_metrics = False
outputs = inpaintor.forward_test(masked_img[0:1], mask[0:1])
for key in ['fake_res', 'fake_img']:
assert outputs[key].size() == (1, 3, 256, 256)
# test forward test w/ save image
with tempfile.TemporaryDirectory() as tmpdir:
outputs = inpaintor.forward_test(
masked_img[0:1],
mask[0:1],
save_image=True,
save_path=tmpdir,
iteration=4396,
meta=[dict(gt_img_path='igccc.png')])
assert os.path.exists(os.path.join(tmpdir, 'igccc_4396.png'))
# test forward test w/ save image w/ gt_img
with tempfile.TemporaryDirectory() as tmpdir:
outputs = inpaintor.forward_test(
masked_img[0:1],
mask[0:1],
save_image=True,
save_path=tmpdir,
meta=[dict(gt_img_path='igccc.png')],
gt_img=gt_img[0:1, ...])
assert os.path.exists(os.path.join(tmpdir, 'igccc.png'))
with pytest.raises(AssertionError):
outputs = inpaintor.forward_test(
masked_img[0:1],
mask[0:1],
save_image=True,
save_path=tmpdir,
iteration=4396,
gt_img=gt_img[0:1, ...])
with pytest.raises(AssertionError):
outputs = inpaintor.forward_test(
masked_img[0:1],
mask[0:1],
save_image=True,
save_path=None,
iteration=4396,
meta=[dict(gt_img_path='igccc.png')],
gt_img=gt_img[0:1, ...])
cfg_ = copy.deepcopy(cfg)
cfg_.train_cfg.disc_step = 2
inpaintor = build_model(
cfg_.model, train_cfg=cfg_.train_cfg, test_cfg=cfg_.test_cfg)
inpaintor.cuda()
assert inpaintor.train_cfg.disc_step == 2
outputs = inpaintor.train_step(data_batch, optim_dict)
assert 'loss_l1_hole' not in outputs['log_vars']
| 6,045 | 39.306667 | 79 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_models/test_inpaintors/test_aot_inpaintor.py | # Copyright (c) OpenMMLab. All rights reserved.
import copy
import os
import tempfile
import pytest
import torch
from mmcv import Config
from mmedit.models import build_model
from mmedit.models.backbones.encoder_decoders import AOTEncoderDecoder
def test_aot_inpaintor():
cfg = Config.fromfile('tests/data/inpaintor_config/aot_test.py')
inpaintor = build_model(
cfg.model, train_cfg=cfg.train_cfg, test_cfg=cfg.test_cfg)
# test attributes
assert inpaintor.__class__.__name__ == 'AOTInpaintor'
assert isinstance(inpaintor.generator, AOTEncoderDecoder)
assert inpaintor.with_l1_valid_loss
assert inpaintor.with_composed_percep_loss
assert inpaintor.with_out_percep_loss
assert inpaintor.with_gan
assert inpaintor.is_train
assert inpaintor.train_cfg['disc_step'] == 1
assert inpaintor.disc_step_count == 0
input_x = torch.randn(1, 3, 256, 256)
with pytest.raises(NotImplementedError):
inpaintor.forward_train(input_x)
gt_img = torch.randn(1, 3, 256, 256)
mask = torch.zeros_like(gt_img)[:, 0:1, ...]
mask[..., 20:100, 100:120] = 1.
masked_img = gt_img * (1. - mask) + mask
inpaintor
data_batch = dict(gt_img=gt_img, mask=mask, masked_img=masked_img)
output = inpaintor.forward_test(**data_batch)
assert 'eval_results' in output
output = inpaintor.val_step(data_batch)
assert 'eval_results' in output
optim_g = torch.optim.SGD(inpaintor.generator.parameters(), lr=0.1)
optim_d = torch.optim.SGD(inpaintor.disc.parameters(), lr=0.1)
optim_dict = dict(generator=optim_g, disc=optim_d)
outputs = inpaintor.train_step(data_batch, optim_dict)
assert outputs['num_samples'] == 1
results = outputs['results']
assert results['fake_res'].shape == (1, 3, 256, 256)
assert 'loss_l1_valid' in outputs['log_vars']
assert 'loss_out_percep' in outputs['log_vars']
assert 'disc_losses' in outputs['log_vars']
assert 'loss_g_fake' in outputs['log_vars']
# test forward test w/o save image
outputs = inpaintor.forward_test(
masked_img[0:1], mask[0:1], gt_img=gt_img[0:1, ...])
assert 'eval_results' in outputs
assert outputs['eval_results']['l1'] > 0
assert outputs['eval_results']['psnr'] > 0
assert outputs['eval_results']['ssim'] > 0
# test forward test w/o eval metrics
inpaintor.test_cfg = dict()
inpaintor.eval_with_metrics = False
outputs = inpaintor.forward_test(masked_img[0:1], mask[0:1])
for key in ['fake_res', 'fake_img']:
assert outputs[key].size() == (1, 3, 256, 256)
# test forward test w/ save image
with tempfile.TemporaryDirectory() as tmpdir:
outputs = inpaintor.forward_test(
masked_img[0:1],
mask[0:1],
save_image=True,
save_path=tmpdir,
iteration=4396,
meta=[dict(gt_img_path='igccc.png')])
assert os.path.exists(os.path.join(tmpdir, 'igccc_4396.png'))
# test forward test w/ save image w/ gt_img
with tempfile.TemporaryDirectory() as tmpdir:
outputs = inpaintor.forward_test(
masked_img[0:1],
mask[0:1],
save_image=True,
save_path=tmpdir,
meta=[dict(gt_img_path='igccc.png')],
gt_img=gt_img[0:1, ...])
assert os.path.exists(os.path.join(tmpdir, 'igccc.png'))
with pytest.raises(AssertionError):
outputs = inpaintor.forward_test(
masked_img[0:1],
mask[0:1],
save_image=True,
save_path=tmpdir,
iteration=4396,
gt_img=gt_img[0:1, ...])
with pytest.raises(AssertionError):
outputs = inpaintor.forward_test(
masked_img[0:1],
mask[0:1],
save_image=True,
save_path=None,
iteration=4396,
meta=[dict(gt_img_path='igccc.png')],
gt_img=gt_img[0:1, ...])
cfg_ = copy.deepcopy(cfg)
cfg_.train_cfg.disc_step = 2
inpaintor = build_model(
cfg_.model, train_cfg=cfg_.train_cfg, test_cfg=cfg_.test_cfg)
assert inpaintor.train_cfg.disc_step == 2
outputs = inpaintor.train_step(data_batch, optim_dict)
assert 'loss_l1_hole' not in outputs['log_vars']
# Test on GPU
if torch.cuda.is_available():
gt_img = torch.randn(1, 3, 256, 256).cuda()
mask = torch.zeros_like(gt_img)[:, 0:1, ...]
mask[..., 20:100, 100:120] = 1.
masked_img = gt_img * (1. - mask) + mask
inpaintor.cuda()
data_batch = dict(gt_img=gt_img, mask=mask, masked_img=masked_img)
output = inpaintor.forward_test(**data_batch)
assert 'eval_results' in output
output = inpaintor.val_step(data_batch)
assert 'eval_results' in output
optim_g = torch.optim.SGD(inpaintor.generator.parameters(), lr=0.1)
optim_d = torch.optim.SGD(inpaintor.disc.parameters(), lr=0.1)
optim_dict = dict(generator=optim_g, disc=optim_d)
outputs = inpaintor.train_step(data_batch, optim_dict)
assert outputs['num_samples'] == 1
results = outputs['results']
assert results['fake_res'].shape == (1, 3, 256, 256)
assert 'loss_l1_valid' in outputs['log_vars']
assert 'loss_out_percep' in outputs['log_vars']
assert 'disc_losses' in outputs['log_vars']
assert 'loss_g_fake' in outputs['log_vars']
# test forward test w/o save image
outputs = inpaintor.forward_test(
masked_img[0:1], mask[0:1], gt_img=gt_img[0:1, ...])
assert 'eval_results' in outputs
assert outputs['eval_results']['l1'] > 0
assert outputs['eval_results']['psnr'] > 0
assert outputs['eval_results']['ssim'] > 0
# test forward test w/o eval metrics
inpaintor.test_cfg = dict()
inpaintor.eval_with_metrics = False
outputs = inpaintor.forward_test(masked_img[0:1], mask[0:1])
for key in ['fake_res', 'fake_img']:
assert outputs[key].size() == (1, 3, 256, 256)
# test forward test w/ save image
with tempfile.TemporaryDirectory() as tmpdir:
outputs = inpaintor.forward_test(
masked_img[0:1],
mask[0:1],
save_image=True,
save_path=tmpdir,
iteration=4396,
meta=[dict(gt_img_path='igccc.png')])
assert os.path.exists(os.path.join(tmpdir, 'igccc_4396.png'))
# test forward test w/ save image w/ gt_img
with tempfile.TemporaryDirectory() as tmpdir:
outputs = inpaintor.forward_test(
masked_img[0:1],
mask[0:1],
save_image=True,
save_path=tmpdir,
meta=[dict(gt_img_path='igccc.png')],
gt_img=gt_img[0:1, ...])
assert os.path.exists(os.path.join(tmpdir, 'igccc.png'))
with pytest.raises(AssertionError):
outputs = inpaintor.forward_test(
masked_img[0:1],
mask[0:1],
save_image=True,
save_path=tmpdir,
iteration=4396,
gt_img=gt_img[0:1, ...])
with pytest.raises(AssertionError):
outputs = inpaintor.forward_test(
masked_img[0:1],
mask[0:1],
save_image=True,
save_path=None,
iteration=4396,
meta=[dict(gt_img_path='igccc.png')],
gt_img=gt_img[0:1, ...])
cfg_ = copy.deepcopy(cfg)
cfg_.train_cfg.disc_step = 2
inpaintor = build_model(
cfg_.model, train_cfg=cfg_.train_cfg, test_cfg=cfg_.test_cfg)
inpaintor.cuda()
assert inpaintor.train_cfg.disc_step == 2
outputs = inpaintor.train_step(data_batch, optim_dict)
assert 'loss_l1_hole' not in outputs['log_vars']
| 8,089 | 36.281106 | 75 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_data/test_datasets/test_repeat_dataset.py | # Copyright (c) OpenMMLab. All rights reserved.
from torch.utils.data import Dataset
from mmedit.datasets import RepeatDataset
def test_repeat_dataset():
class ToyDataset(Dataset):
def __init__(self):
super().__init__()
self.members = [1, 2, 3, 4, 5]
def __len__(self):
return len(self.members)
def __getitem__(self, idx):
return self.members[idx % 5]
toy_dataset = ToyDataset()
repeat_dataset = RepeatDataset(toy_dataset, 2)
assert len(repeat_dataset) == 10
assert repeat_dataset[2] == 3
assert repeat_dataset[8] == 4
| 623 | 23 | 50 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_data/test_pipelines/test_formating.py | # Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
import pytest
import torch
from mmedit.datasets.pipelines import (Collect, FormatTrimap, GetMaskedImage,
ImageToTensor, ToTensor)
from mmedit.datasets.pipelines.formating import FramesToTensor
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.randn(2, 3),
sequence=list(range(10)),
int=1,
float=0.1)
results = to_tensor(ori_results)
assert check_keys_contain(results.keys(), target_keys)
for key in target_keys:
assert isinstance(results[key], torch.Tensor)
assert torch.equal(results[key].data, ori_results[key])
# Add an additional key which is not in keys.
ori_results = dict(
tensor=torch.randn(2, 3),
numpy=np.random.randn(2, 3),
sequence=list(range(10)),
int=1,
float=0.1,
str='test')
results = to_tensor(ori_results)
assert check_keys_contain(results.keys(), target_keys)
for key in target_keys:
assert isinstance(results[key], torch.Tensor)
assert torch.equal(results[key].data, ori_results[key])
assert repr(
to_tensor) == to_tensor.__class__.__name__ + f'(keys={target_keys})'
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.Tensor)
assert torch.equal(results['img'].data, ori_results['img'])
assert results['img'].dtype == torch.float32
ori_results = dict(img=np.random.randint(256, size=(256, 256)))
keys = ['img']
to_float32 = True
image_to_tensor = ImageToTensor(keys)
results = image_to_tensor(ori_results)
assert results['img'].shape == torch.Size([1, 256, 256])
assert isinstance(results['img'], torch.Tensor)
assert torch.equal(results['img'].data, ori_results['img'])
assert results['img'].dtype == torch.float32
assert repr(image_to_tensor) == (
image_to_tensor.__class__.__name__ +
f'(keys={keys}, to_float32={to_float32})')
def test_frames_to_tensor():
with pytest.raises(TypeError):
# results[key] should be a list
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_float32=False)
results = frames_to_tensor(ori_results)
assert results['img'].shape == torch.Size([2, 3, 12, 12])
assert isinstance(results['img'], torch.Tensor)
assert torch.equal(results['img'].data[0, ...], ori_results['img'][0])
assert torch.equal(results['img'].data[1, ...], ori_results['img'][1])
assert results['img'].dtype == torch.float64
ori_results = dict(
img=[np.random.randn(12, 12, 3),
np.random.randn(12, 12, 3)])
frames_to_tensor = FramesToTensor(keys, to_float32=True)
results = frames_to_tensor(ori_results)
assert results['img'].shape == torch.Size([2, 3, 12, 12])
assert isinstance(results['img'], torch.Tensor)
assert torch.equal(results['img'].data[0, ...], ori_results['img'][0])
assert torch.equal(results['img'].data[1, ...], ori_results['img'][1])
assert results['img'].dtype == torch.float32
ori_results = dict(img=[np.random.randn(12, 12), np.random.randn(12, 12)])
frames_to_tensor = FramesToTensor(keys, to_float32=True)
results = frames_to_tensor(ori_results)
assert results['img'].shape == torch.Size([2, 1, 12, 12])
assert isinstance(results['img'], torch.Tensor)
assert torch.equal(results['img'].data[0, ...], ori_results['img'][0])
assert torch.equal(results['img'].data[1, ...], ori_results['img'][1])
assert results['img'].dtype == torch.float32
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. - mask)
assert np.array_equal(results['masked_img'], masked_img)
name_ = repr(get_masked_img)
class_name = get_masked_img.__class__.__name__
assert name_ == class_name + "(img_name='gt_img', mask_name='mask')"
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 = FormatTrimap(to_onehot=False)
results = format_trimap(ori_result)
result_trimap = results['trimap']
assert result_trimap.shape == (1, 64, 64)
assert ((result_trimap.numpy() == 0) == (ori_trimap == 0)).all()
assert ((result_trimap.numpy() == 1) == (ori_trimap == 128)).all()
assert ((result_trimap.numpy() == 2) == (ori_trimap == 255)).all()
ori_result = dict(
trimap=torch.from_numpy(ori_trimap.copy()), meta=DataContainer({}))
format_trimap = FormatTrimap(to_onehot=True)
results = format_trimap(ori_result)
result_trimap = results['trimap']
assert result_trimap.shape == (3, 64, 64)
assert ((result_trimap[0, ...].numpy() == 1) == (ori_trimap == 0)).all()
assert ((result_trimap[1, ...].numpy() == 1) == (ori_trimap == 128)).all()
assert ((result_trimap[2, ...].numpy() == 1) == (ori_trimap == 255)).all()
assert repr(format_trimap) == format_trimap.__class__.__name__ + (
'(to_onehot=True)')
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', 'ori_shape']
collect = Collect(keys, meta_keys=meta_keys)
results = collect(inputs)
assert set(list(results.keys())) == set(['img', 'label', 'meta'])
inputs.pop('img')
assert set(results['meta'].data.keys()) == set(meta_keys)
for key in results['meta'].data:
assert results['meta'].data[key] == inputs[key]
assert repr(collect) == (
collect.__class__.__name__ +
f'(keys={keys}, meta_keys={collect.meta_keys})')
| 7,142 | 36.793651 | 78 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_data/test_pipelines/test_generate_assistant.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch
from mmedit.datasets.pipelines import (GenerateCoordinateAndCell,
GenerateHeatmap)
def test_generate_heatmap():
inputs = dict(landmark=[(1, 2), (3, 4)])
generate_heatmap = GenerateHeatmap('landmark', 4, 16)
results = generate_heatmap(inputs)
assert set(list(results.keys())) == set(['landmark', 'heatmap'])
assert results['heatmap'][:, :, 0].shape == (16, 16)
assert repr(generate_heatmap) == (
f'{generate_heatmap.__class__.__name__}, '
f'keypoint={generate_heatmap.keypoint}, '
f'ori_size={generate_heatmap.ori_size}, '
f'target_size={generate_heatmap.target_size}, '
f'sigma={generate_heatmap.sigma}')
generate_heatmap = GenerateHeatmap('landmark', (4, 5), (16, 17))
results = generate_heatmap(inputs)
assert set(list(results.keys())) == set(['landmark', 'heatmap'])
assert results['heatmap'][:, :, 0].shape == (17, 16)
def test_generate_coordinate_and_cell():
tensor1 = torch.randn((3, 64, 48))
inputs1 = dict(lq=tensor1)
coordinate1 = GenerateCoordinateAndCell(scale=3.1, target_size=(128, 96))
results1 = coordinate1(inputs1)
assert set(list(results1.keys())) == set(['lq', 'coord', 'cell'])
assert repr(coordinate1) == (
coordinate1.__class__.__name__ +
f'sample_quantity={coordinate1.sample_quantity}, ' +
f'scale={coordinate1.scale}, ' +
f'target_size={coordinate1.target_size}')
tensor2 = torch.randn((3, 64, 48))
inputs2 = dict(gt=tensor2)
coordinate2 = GenerateCoordinateAndCell(
sample_quantity=64 * 48, scale=3.1, target_size=(128, 96))
results2 = coordinate2(inputs2)
assert set(list(results2.keys())) == set(['gt', 'coord', 'cell'])
assert results2['gt'].shape == (64 * 48, 3)
inputs3 = dict()
coordinate3 = GenerateCoordinateAndCell(
sample_quantity=64 * 48, scale=3.1, target_size=(128, 96))
results3 = coordinate3(inputs3)
assert set(list(results3.keys())) == set(['coord', 'cell'])
| 2,102 | 39.442308 | 77 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_data/test_pipelines/test_pipeline_utils.py | # Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
import pytest
import torch
from mmedit.datasets.pipelines.utils import (adjust_gamma, dtype_range,
make_coord)
def test_adjust_gamma():
"""Test Gamma Correction
Adpted from
# https://github.com/scikit-image/scikit-image/blob/7e4840bd9439d1dfb6beaf549998452c99f97fdd/skimage/exposure/tests/test_exposure.py#L534 # noqa
"""
# Check that the shape is maintained.
img = np.ones([1, 1])
result = adjust_gamma(img, 1.5)
assert img.shape == result.shape
# Same image should be returned for gamma equal to one.
image = np.random.uniform(0, 255, (8, 8))
result = adjust_gamma(image, 1)
np.testing.assert_array_equal(result, image)
# White image should be returned for gamma equal to zero.
image = np.random.uniform(0, 255, (8, 8))
result = adjust_gamma(image, 0)
dtype = image.dtype.type
np.testing.assert_array_equal(result, dtype_range[dtype][1])
# Verifying the output with expected results for gamma
# correction with gamma equal to half.
image = np.arange(0, 255, 4, np.uint8).reshape((8, 8))
expected = np.array([[0, 31, 45, 55, 63, 71, 78, 84],
[90, 95, 100, 105, 110, 115, 119, 123],
[127, 131, 135, 139, 142, 146, 149, 153],
[156, 159, 162, 165, 168, 171, 174, 177],
[180, 183, 186, 188, 191, 194, 196, 199],
[201, 204, 206, 209, 211, 214, 216, 218],
[221, 223, 225, 228, 230, 232, 234, 236],
[238, 241, 243, 245, 247, 249, 251, 253]],
dtype=np.uint8)
result = adjust_gamma(image, 0.5)
np.testing.assert_array_equal(result, expected)
# Verifying the output with expected results for gamma
# correction with gamma equal to two.
image = np.arange(0, 255, 4, np.uint8).reshape((8, 8))
expected = np.array([[0, 0, 0, 0, 1, 1, 2, 3], [4, 5, 6, 7, 9, 10, 12, 14],
[16, 18, 20, 22, 25, 27, 30, 33],
[36, 39, 42, 45, 49, 52, 56, 60],
[64, 68, 72, 76, 81, 85, 90, 95],
[100, 105, 110, 116, 121, 127, 132, 138],
[144, 150, 156, 163, 169, 176, 182, 189],
[196, 203, 211, 218, 225, 233, 241, 249]],
dtype=np.uint8)
result = adjust_gamma(image, 2)
np.testing.assert_array_equal(result, expected)
# Test invalid image input
image = np.arange(0, 255, 4, np.uint8).reshape((8, 8))
with pytest.raises(ValueError):
adjust_gamma(image, -1)
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)
test_make_coord()
| 3,075 | 36.512195 | 149 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_data/test_pipelines/test_augmentation.py | # Copyright (c) OpenMMLab. All rights reserved.
import copy
import os.path as osp
import numpy as np
import pytest
import torch
# yapf: disable
from mmedit.datasets.pipelines import (BinarizeImage, ColorJitter, CopyValues,
Flip, GenerateFrameIndices,
GenerateFrameIndiceswithPadding,
GenerateSegmentIndices, MirrorSequence,
Pad, Quantize, RandomAffine,
RandomJitter, RandomMaskDilation,
RandomTransposeHW, Resize,
TemporalReverse, UnsharpMasking)
from mmedit.datasets.pipelines.augmentation import RandomRotation
class TestAugmentations:
@classmethod
def setup_class(cls):
cls.results = dict()
cls.img_gt = np.random.rand(256, 128, 3).astype(np.float32)
cls.img_lq = np.random.rand(64, 32, 3).astype(np.float32)
cls.results = dict(
lq=cls.img_lq,
gt=cls.img_gt,
scale=4,
lq_path='fake_lq_path',
gt_path='fake_gt_path')
cls.results['img'] = np.random.rand(256, 256, 3).astype(np.float32)
cls.results['mask'] = np.random.rand(256, 256, 1).astype(np.float32)
cls.results['img_tensor'] = torch.rand((3, 256, 256))
cls.results['mask_tensor'] = torch.zeros((1, 256, 256))
cls.results['mask_tensor'][:, 50:150, 40:140] = 1.
@staticmethod
def assert_img_equal(img, ref_img, ratio_thr=0.999):
"""Check if img and ref_img are matched approximately."""
assert img.shape == ref_img.shape
assert img.dtype == ref_img.dtype
area = ref_img.shape[-1] * ref_img.shape[-2]
diff = np.abs(img.astype('int32') - ref_img.astype('int32'))
assert np.sum(diff <= 1) / float(area) > ratio_thr
@staticmethod
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))
@staticmethod
def check_flip(origin_img, result_img, flip_type):
"""Check if the origin_img are flipped correctly into result_img
in different flip_types"""
h, w, c = origin_img.shape
if flip_type == 'horizontal':
for i in range(h):
for j in range(w):
for k in range(c):
if result_img[i, j, k] != origin_img[i, w - 1 - j, k]:
return False
else:
for i in range(h):
for j in range(w):
for k in range(c):
if result_img[i, j, k] != origin_img[h - 1 - i, j, k]:
return False
return True
def test_binarize(self):
mask_ = np.zeros((5, 5, 1))
mask_[2, 2, :] = 0.6
gt_mask = mask_.copy()
gt_mask[2, 2, :] = 1.
results = dict(mask=mask_.copy())
binarize = BinarizeImage(['mask'], 0.5, to_int=False)
results = binarize(results)
assert np.array_equal(results['mask'], gt_mask.astype(np.float32))
results = dict(mask=mask_.copy())
binarize = BinarizeImage(['mask'], 0.5, to_int=True)
results = binarize(results)
assert np.array_equal(results['mask'], gt_mask.astype(np.int32))
assert str(binarize) == (
binarize.__class__.__name__ +
f"(keys={['mask']}, binary_thr=0.5, to_int=True)")
def test_flip(self):
results = copy.deepcopy(self.results)
with pytest.raises(ValueError):
Flip(keys=['lq', 'gt'], direction='vertically')
# horizontal
np.random.seed(1)
target_keys = ['lq', 'gt', 'flip', 'flip_direction']
flip = Flip(keys=['lq', 'gt'], flip_ratio=1, direction='horizontal')
results = flip(results)
assert self.check_keys_contain(results.keys(), target_keys)
assert self.check_flip(self.img_lq, results['lq'],
results['flip_direction'])
assert self.check_flip(self.img_gt, results['gt'],
results['flip_direction'])
assert results['lq'].shape == self.img_lq.shape
assert results['gt'].shape == self.img_gt.shape
# vertical
results = copy.deepcopy(self.results)
flip = Flip(keys=['lq', 'gt'], flip_ratio=1, direction='vertical')
results = flip(results)
assert self.check_keys_contain(results.keys(), target_keys)
assert self.check_flip(self.img_lq, results['lq'],
results['flip_direction'])
assert self.check_flip(self.img_gt, results['gt'],
results['flip_direction'])
assert results['lq'].shape == self.img_lq.shape
assert results['gt'].shape == self.img_gt.shape
assert repr(flip) == flip.__class__.__name__ + (
f"(keys={['lq', 'gt']}, flip_ratio=1, "
f"direction={results['flip_direction']})")
# flip a list
# horizontal
flip = Flip(keys=['lq', 'gt'], flip_ratio=1, direction='horizontal')
results = dict(
lq=[self.img_lq, np.copy(self.img_lq)],
gt=[self.img_gt, np.copy(self.img_gt)],
scale=4,
lq_path='fake_lq_path',
gt_path='fake_gt_path')
flip_rlt = flip(copy.deepcopy(results))
assert self.check_keys_contain(flip_rlt.keys(), target_keys)
assert self.check_flip(self.img_lq, flip_rlt['lq'][0],
flip_rlt['flip_direction'])
assert self.check_flip(self.img_gt, flip_rlt['gt'][0],
flip_rlt['flip_direction'])
np.testing.assert_almost_equal(flip_rlt['gt'][0], flip_rlt['gt'][1])
np.testing.assert_almost_equal(flip_rlt['lq'][0], flip_rlt['lq'][1])
# vertical
flip = Flip(keys=['lq', 'gt'], flip_ratio=1, direction='vertical')
flip_rlt = flip(copy.deepcopy(results))
assert self.check_keys_contain(flip_rlt.keys(), target_keys)
assert self.check_flip(self.img_lq, flip_rlt['lq'][0],
flip_rlt['flip_direction'])
assert self.check_flip(self.img_gt, flip_rlt['gt'][0],
flip_rlt['flip_direction'])
np.testing.assert_almost_equal(flip_rlt['gt'][0], flip_rlt['gt'][1])
np.testing.assert_almost_equal(flip_rlt['lq'][0], flip_rlt['lq'][1])
# no flip
flip = Flip(keys=['lq', 'gt'], flip_ratio=0, direction='vertical')
results = flip(copy.deepcopy(results))
assert self.check_keys_contain(results.keys(), target_keys)
np.testing.assert_almost_equal(results['gt'][0], self.img_gt)
np.testing.assert_almost_equal(results['lq'][0], self.img_lq)
np.testing.assert_almost_equal(results['gt'][0], results['gt'][1])
np.testing.assert_almost_equal(results['lq'][0], results['lq'][1])
def test_pad(self):
target_keys = ['alpha']
alpha = np.random.rand(319, 321).astype(np.float32)
results = dict(alpha=alpha)
pad = Pad(keys=['alpha'], ds_factor=32, mode='constant')
pad_results = pad(results)
assert self.check_keys_contain(pad_results.keys(), target_keys)
assert pad_results['alpha'].shape == (320, 352)
assert self.check_pad(alpha, results['alpha'], 'constant')
alpha = np.random.rand(319, 321).astype(np.float32)
results = dict(alpha=alpha)
pad = Pad(keys=['alpha'], ds_factor=32, mode='reflect')
pad_results = pad(results)
assert self.check_keys_contain(pad_results.keys(), target_keys)
assert pad_results['alpha'].shape == (320, 352)
assert self.check_pad(alpha, results['alpha'], 'reflect')
alpha = np.random.rand(320, 320).astype(np.float32)
results = dict(alpha=alpha)
pad = Pad(keys=['alpha'], ds_factor=32, mode='reflect')
pad_results = pad(results)
assert self.check_keys_contain(pad_results.keys(), target_keys)
assert pad_results['alpha'].shape == (320, 320)
assert self.check_pad(alpha, results['alpha'], 'reflect')
assert repr(pad) == pad.__class__.__name__ + (
f"(keys={['alpha']}, ds_factor=32, mode={'reflect'})")
@staticmethod
def check_pad(origin_img, result_img, mode, ds_factor=32):
"""Check if the origin_img is padded correctly.
Supported modes for checking are 'constant' (with 'constant_values' of
0) and 'reflect'.
Supported images should be 2 dimensional.
"""
if mode not in ['constant', 'reflect']:
raise NotImplementedError(
f'Pad checking of mode {mode} is not implemented.')
assert len(origin_img.shape) == 2, 'Image should be 2 dimensional.'
h, w = origin_img.shape
new_h = ds_factor * (h - 1) // ds_factor + 1
new_w = ds_factor * (w - 1) // ds_factor + 1
# check the bottom rectangle
for i in range(h, new_h):
for j in range(0, w):
target = origin_img[h - i, j] if mode == 'reflect' else 0
if result_img[i, j] != target:
return False
# check the right rectangle
for i in range(0, h):
for j in range(w, new_w):
target = origin_img[i, w - j] if mode == 'reflect' else 0
if result_img[i, j] != target:
return False
# check the bottom right rectangle
for i in range(h, new_h):
for j in range(w, new_w):
target = origin_img[h - i, w - j] if mode == 'reflect' else 0
if result_img[i, j] != target:
return False
return True
def test_random_affine(self):
with pytest.raises(AssertionError):
RandomAffine(None, -1)
with pytest.raises(AssertionError):
RandomAffine(None, 0, translate='Not a tuple')
with pytest.raises(AssertionError):
RandomAffine(None, 0, translate=(0, 0, 0))
with pytest.raises(AssertionError):
RandomAffine(None, 0, translate=(0, 2))
with pytest.raises(AssertionError):
RandomAffine(None, 0, scale='Not a tuple')
with pytest.raises(AssertionError):
RandomAffine(None, 0, scale=(0.8, 1., 1.2))
with pytest.raises(AssertionError):
RandomAffine(None, 0, scale=(-0.8, 1.))
with pytest.raises(AssertionError):
RandomAffine(None, 0, shear=-1)
with pytest.raises(AssertionError):
RandomAffine(None, 0, shear=(0, 1, 2))
with pytest.raises(AssertionError):
RandomAffine(None, 0, flip_ratio='Not a float')
target_keys = ['fg', 'alpha']
# Test identical transformation
alpha = np.random.rand(4, 4).astype(np.float32)
fg = np.random.rand(4, 4).astype(np.float32)
results = dict(alpha=alpha, fg=fg)
random_affine = RandomAffine(['fg', 'alpha'],
degrees=0, flip_ratio=0.0)
random_affine_results = random_affine(results)
assert np.allclose(alpha, random_affine_results['alpha'])
assert np.allclose(fg, random_affine_results['fg'])
# Test flip in both direction
alpha = np.random.rand(4, 4).astype(np.float32)
fg = np.random.rand(4, 4).astype(np.float32)
results = dict(alpha=alpha, fg=fg)
random_affine = RandomAffine(['fg', 'alpha'],
degrees=0, flip_ratio=1.0)
random_affine_results = random_affine(results)
assert np.allclose(alpha[::-1, ::-1], random_affine_results['alpha'])
assert np.allclose(fg[::-1, ::-1], random_affine_results['fg'])
# test random affine with different valid setting combinations
# only shape are tested
alpha = np.random.rand(240, 320).astype(np.float32)
fg = np.random.rand(240, 320).astype(np.float32)
results = dict(alpha=alpha, fg=fg)
random_affine = RandomAffine(['fg', 'alpha'],
degrees=30,
translate=(0, 1),
shear=(10, 20),
flip_ratio=0.5)
random_affine_results = random_affine(results)
assert self.check_keys_contain(random_affine_results.keys(),
target_keys)
assert random_affine_results['fg'].shape == (240, 320)
assert random_affine_results['alpha'].shape == (240, 320)
alpha = np.random.rand(240, 320).astype(np.float32)
fg = np.random.rand(240, 320).astype(np.float32)
results = dict(alpha=alpha, fg=fg)
random_affine = RandomAffine(['fg', 'alpha'],
degrees=(-30, 30),
scale=(0.8, 1.25),
shear=10,
flip_ratio=0.5)
random_affine_results = random_affine(results)
assert self.check_keys_contain(random_affine_results.keys(),
target_keys)
assert random_affine_results['fg'].shape == (240, 320)
assert random_affine_results['alpha'].shape == (240, 320)
alpha = np.random.rand(240, 320).astype(np.float32)
fg = np.random.rand(240, 320).astype(np.float32)
results = dict(alpha=alpha, fg=fg)
random_affine = RandomAffine(['fg', 'alpha'], degrees=30)
random_affine_results = random_affine(results)
assert self.check_keys_contain(random_affine_results.keys(),
target_keys)
assert random_affine_results['fg'].shape == (240, 320)
assert random_affine_results['alpha'].shape == (240, 320)
assert repr(random_affine) == random_affine.__class__.__name__ + (
f'(keys={target_keys}, degrees={(-30, 30)}, '
f'translate={None}, scale={None}, '
f'shear={None}, flip_ratio={0})')
def test_random_jitter(self):
with pytest.raises(AssertionError):
RandomJitter(-40)
with pytest.raises(AssertionError):
RandomJitter((-40, 40, 40))
target_keys = ['fg']
fg = np.random.rand(240, 320, 3).astype(np.float32)
alpha = np.random.rand(240, 320).astype(np.float32)
results = dict(fg=fg.copy(), alpha=alpha)
random_jitter = RandomJitter(40)
random_jitter_results = random_jitter(results)
assert self.check_keys_contain(random_jitter_results.keys(),
target_keys)
assert random_jitter_results['fg'].shape == (240, 320, 3)
fg = np.random.rand(240, 320, 3).astype(np.float32)
alpha = np.random.rand(240, 320).astype(np.float32)
results = dict(fg=fg.copy(), alpha=alpha)
random_jitter = RandomJitter((-50, 50))
random_jitter_results = random_jitter(results)
assert self.check_keys_contain(random_jitter_results.keys(),
target_keys)
assert random_jitter_results['fg'].shape == (240, 320, 3)
assert repr(random_jitter) == random_jitter.__class__.__name__ + (
'hue_range=(-50, 50)')
def test_color_jitter(self):
results = copy.deepcopy(self.results)
results['gt'] = (results['gt'] * 255).astype(np.uint8)
target_keys = ['gt']
color_jitter = ColorJitter(
keys=['gt'], brightness=0.5, contrast=0.5, saturation=0.5, hue=0.5)
color_jitter_results = color_jitter(results)
assert self.check_keys_contain(color_jitter_results.keys(),
target_keys)
assert color_jitter_results['gt'].shape == self.img_gt.shape
assert repr(color_jitter) == color_jitter.__class__.__name__ + (
f"(keys=['gt'], to_rgb=False)")
@staticmethod
def check_transposehw(origin_img, result_img):
"""Check if the origin_imgs are transposed correctly"""
h, w, c = origin_img.shape
for i in range(c):
for j in range(h):
for k in range(w):
if result_img[k, j, i] != origin_img[j, k, i]: # noqa:E501
return False
return True
def test_transposehw(self):
results = self.results.copy()
target_keys = ['lq', 'gt', 'transpose']
transposehw = RandomTransposeHW(keys=['lq', 'gt'], transpose_ratio=1)
results = transposehw(results)
assert self.check_keys_contain(results.keys(), target_keys)
assert self.check_transposehw(self.img_lq, results['lq'])
assert self.check_transposehw(self.img_gt, results['gt'])
assert results['lq'].shape == (32, 64, 3)
assert results['gt'].shape == (128, 256, 3)
assert repr(transposehw) == transposehw.__class__.__name__ + (
f"(keys={['lq', 'gt']}, transpose_ratio=1)")
# for image list
ori_results = dict(
lq=[self.img_lq, np.copy(self.img_lq)],
gt=[self.img_gt, np.copy(self.img_gt)],
scale=4,
lq_path='fake_lq_path',
gt_path='fake_gt_path')
target_keys = ['lq', 'gt', 'transpose']
transposehw = RandomTransposeHW(keys=['lq', 'gt'], transpose_ratio=1)
results = transposehw(ori_results.copy())
assert self.check_keys_contain(results.keys(), target_keys)
assert self.check_transposehw(self.img_lq, results['lq'][0])
assert self.check_transposehw(self.img_gt, results['gt'][1])
np.testing.assert_almost_equal(results['gt'][0], results['gt'][1])
np.testing.assert_almost_equal(results['lq'][0], results['lq'][1])
# no transpose
target_keys = ['lq', 'gt', 'transpose']
transposehw = RandomTransposeHW(keys=['lq', 'gt'], transpose_ratio=0)
results = transposehw(ori_results.copy())
assert self.check_keys_contain(results.keys(), target_keys)
np.testing.assert_almost_equal(results['gt'][0], self.img_gt)
np.testing.assert_almost_equal(results['lq'][0], self.img_lq)
np.testing.assert_almost_equal(results['gt'][0], results['gt'][1])
np.testing.assert_almost_equal(results['lq'][0], results['lq'][1])
def test_random_dilation(self):
mask = np.zeros((3, 3, 1), dtype=np.float32)
mask[1, 1] = 1
gt_mask = np.ones_like(mask)
results = dict(mask=mask.copy())
dilation = RandomMaskDilation(['mask'],
binary_thr=0.5,
kernel_min=3,
kernel_max=3)
results = dilation(results)
assert np.array_equal(results['mask'], gt_mask)
assert results['mask_dilate_kernel_size'] == 3
assert str(dilation) == (
dilation.__class__.__name__ +
f"(keys={['mask']}, kernel_min=3, kernel_max=3)")
def test_resize(self):
with pytest.raises(AssertionError):
Resize([], scale=0.5)
with pytest.raises(AssertionError):
Resize(['gt_img'], size_factor=32, scale=0.5)
with pytest.raises(AssertionError):
Resize(['gt_img'], size_factor=32, keep_ratio=True)
with pytest.raises(AssertionError):
Resize(['gt_img'], max_size=32, size_factor=None)
with pytest.raises(ValueError):
Resize(['gt_img'], scale=-0.5)
with pytest.raises(TypeError):
Resize(['gt_img'], (0.4, 0.2))
with pytest.raises(TypeError):
Resize(['gt_img'], dict(test=None))
target_keys = ['alpha']
alpha = np.random.rand(240, 320).astype(np.float32)
results = dict(alpha=alpha)
resize = Resize(keys=['alpha'], size_factor=32, max_size=None)
resize_results = resize(results)
assert self.check_keys_contain(resize_results.keys(), target_keys)
assert resize_results['alpha'].shape == (224, 320, 1)
resize = Resize(keys=['alpha'], size_factor=32, max_size=320)
resize_results = resize(results)
assert self.check_keys_contain(resize_results.keys(), target_keys)
assert resize_results['alpha'].shape == (224, 320, 1)
resize = Resize(keys=['alpha'], size_factor=32, max_size=200)
resize_results = resize(results)
assert self.check_keys_contain(resize_results.keys(), target_keys)
assert resize_results['alpha'].shape == (192, 192, 1)
resize = Resize(['gt_img'], (-1, 200))
assert resize.scale == (np.inf, 200)
results = dict(gt_img=self.results['img'].copy())
resize_keep_ratio = Resize(['gt_img'], scale=0.5, keep_ratio=True)
results = resize_keep_ratio(results)
assert results['gt_img'].shape[:2] == (128, 128)
assert results['scale_factor'] == 0.5
results = dict(gt_img=self.results['img'].copy())
resize_keep_ratio = Resize(['gt_img'],
scale=(128, 128),
keep_ratio=False)
results = resize_keep_ratio(results)
assert results['gt_img'].shape[:2] == (128, 128)
# test input with shape (256, 256)
results = dict(gt_img=self.results['img'][..., 0].copy(), alpha=alpha)
resize = Resize(['gt_img', 'alpha'],
scale=(128, 128),
keep_ratio=False,
output_keys=['lq_img', 'beta'])
results = resize(results)
assert results['gt_img'].shape == (256, 256)
assert results['lq_img'].shape == (128, 128, 1)
assert results['alpha'].shape == (240, 320)
assert results['beta'].shape == (128, 128, 1)
name_ = str(resize_keep_ratio)
assert name_ == resize_keep_ratio.__class__.__name__ + (
"(keys=['gt_img'], output_keys=['gt_img'], "
'scale=(128, 128), '
f'keep_ratio={False}, size_factor=None, '
'max_size=None, interpolation=bilinear)')
def test_random_rotation(self):
with pytest.raises(ValueError):
RandomRotation(None, degrees=-10.0)
with pytest.raises(TypeError):
RandomRotation(None, degrees=('0.0', '45.0'))
target_keys = ['degrees']
results = copy.deepcopy(self.results)
random_rotation = RandomRotation(['img'], degrees=(0, 45))
random_rotation_results = random_rotation(results)
assert self.check_keys_contain(
random_rotation_results.keys(), target_keys)
assert random_rotation_results['img'].shape == (256, 256, 3)
assert random_rotation_results['degrees'] == (0, 45)
assert repr(random_rotation) == random_rotation.__class__.__name__ + (
"(keys=['img'], degrees=(0, 45))")
# test single degree integer
random_rotation = RandomRotation(['img'], degrees=45)
random_rotation_results = random_rotation(results)
assert self.check_keys_contain(
random_rotation_results.keys(), target_keys)
assert random_rotation_results['img'].shape == (256, 256, 3)
assert random_rotation_results['degrees'] == (-45, 45)
# test image dim == 2
grey_scale_img = np.random.rand(256, 256).astype(np.float32)
results = dict(img=grey_scale_img.copy())
random_rotation = RandomRotation(['img'], degrees=(0, 45))
random_rotation_results = random_rotation(results)
assert self.check_keys_contain(
random_rotation_results.keys(), target_keys)
assert random_rotation_results['img'].shape == (256, 256, 1)
def test_frame_index_generation_with_padding(self):
with pytest.raises(ValueError):
# Wrong padding mode
GenerateFrameIndiceswithPadding(padding='fake')
results = dict(
lq_path='fake_lq_root',
gt_path='fake_gt_root',
key=osp.join('000', '00000000'),
max_frame_num=100,
num_input_frames=5)
target_keys = ['lq_path', 'gt_path', 'key']
replicate_idx = [0, 0, 0, 1, 2]
reflection_idx = [2, 1, 0, 1, 2]
reflection_circle_idx = [4, 3, 0, 1, 2]
circle_idx = [3, 4, 0, 1, 2]
# replicate
lq_paths = [osp.join('fake_lq_root', '000',
f'{v:08d}.png') for v in replicate_idx]
gt_paths = [osp.join('fake_gt_root', '000', '00000000.png')]
frame_index_generator = GenerateFrameIndiceswithPadding(
padding='replicate')
rlt = frame_index_generator(copy.deepcopy(results))
assert self.check_keys_contain(rlt.keys(), target_keys)
assert rlt['lq_path'] == lq_paths
assert rlt['gt_path'] == gt_paths
# reflection
lq_paths = [osp.join('fake_lq_root', '000',
f'{v:08d}.png') for v in reflection_idx]
frame_index_generator = GenerateFrameIndiceswithPadding(
padding='reflection')
rlt = frame_index_generator(copy.deepcopy(results))
assert rlt['lq_path'] == lq_paths
assert rlt['gt_path'] == gt_paths
# reflection_circle
lq_paths = [
osp.join('fake_lq_root', '000',
f'{v:08d}.png') for v in reflection_circle_idx
]
frame_index_generator = GenerateFrameIndiceswithPadding(
padding='reflection_circle')
rlt = frame_index_generator(copy.deepcopy(results))
assert rlt['lq_path'] == lq_paths
assert rlt['gt_path'] == gt_paths
# circle
lq_paths = [osp.join('fake_lq_root', '000',
f'{v:08d}.png') for v in circle_idx]
frame_index_generator = GenerateFrameIndiceswithPadding(
padding='circle')
rlt = frame_index_generator(copy.deepcopy(results))
assert rlt['lq_path'] == lq_paths
assert rlt['gt_path'] == gt_paths
results = dict(
lq_path='fake_lq_root',
gt_path='fake_gt_root',
key=osp.join('000', '00000099'),
max_frame_num=100,
num_input_frames=5)
target_keys = ['lq_path', 'gt_path', 'key']
replicate_idx = [97, 98, 99, 99, 99]
reflection_idx = [97, 98, 99, 98, 97]
reflection_circle_idx = [97, 98, 99, 96, 95]
circle_idx = [97, 98, 99, 95, 96]
# replicate
lq_paths = [osp.join('fake_lq_root', '000',
f'{v:08d}.png') for v in replicate_idx]
gt_paths = [osp.join('fake_gt_root', '000', '00000099.png')]
frame_index_generator = GenerateFrameIndiceswithPadding(
padding='replicate')
rlt = frame_index_generator(copy.deepcopy(results))
assert self.check_keys_contain(rlt.keys(), target_keys)
assert rlt['lq_path'] == lq_paths
assert rlt['gt_path'] == gt_paths
# reflection
lq_paths = [osp.join('fake_lq_root', '000',
f'{v:08d}.png') for v in reflection_idx]
frame_index_generator = GenerateFrameIndiceswithPadding(
padding='reflection')
rlt = frame_index_generator(copy.deepcopy(results))
assert rlt['lq_path'] == lq_paths
assert rlt['gt_path'] == gt_paths
# reflection_circle
lq_paths = [
osp.join('fake_lq_root', '000',
f'{v:08d}.png') for v in reflection_circle_idx
]
frame_index_generator = GenerateFrameIndiceswithPadding(
padding='reflection_circle')
rlt = frame_index_generator(copy.deepcopy(results))
assert rlt['lq_path'] == lq_paths
assert rlt['gt_path'] == gt_paths
# circle
lq_paths = [osp.join('fake_lq_root', '000',
f'{v:08d}.png') for v in circle_idx]
frame_index_generator = GenerateFrameIndiceswithPadding(
padding='circle')
rlt = frame_index_generator(copy.deepcopy(results))
assert rlt['lq_path'] == lq_paths
assert rlt['gt_path'] == gt_paths
name_ = repr(frame_index_generator)
assert name_ == frame_index_generator.__class__.__name__ + (
"(padding='circle')")
def test_frame_index_generator(self):
results = dict(
lq_path='fake_lq_root',
gt_path='fake_gt_root',
key=osp.join('000', '00000010'),
num_input_frames=3)
target_keys = ['lq_path', 'gt_path', 'key', 'interval']
frame_index_generator = GenerateFrameIndices(
interval_list=[1], frames_per_clip=99)
rlt = frame_index_generator(copy.deepcopy(results))
assert self.check_keys_contain(rlt.keys(), target_keys)
name_ = repr(frame_index_generator)
assert name_ == frame_index_generator.__class__.__name__ + (
'(interval_list=[1], frames_per_clip=99)')
# index out of range
frame_index_generator = GenerateFrameIndices(interval_list=[10])
rlt = frame_index_generator(copy.deepcopy(results))
assert self.check_keys_contain(rlt.keys(), target_keys)
# index out of range
results['key'] = osp.join('000', '00000099')
frame_index_generator = GenerateFrameIndices(interval_list=[2, 3])
rlt = frame_index_generator(copy.deepcopy(results))
assert self.check_keys_contain(rlt.keys(), target_keys)
def test_temporal_reverse(self):
img_lq1 = np.random.rand(4, 4, 3).astype(np.float32)
img_lq2 = np.random.rand(4, 4, 3).astype(np.float32)
img_gt = np.random.rand(8, 8, 3).astype(np.float32)
results = dict(lq=[img_lq1, img_lq2], gt=[img_gt])
target_keys = ['lq', 'gt', 'reverse']
temporal_reverse = TemporalReverse(keys=['lq', 'gt'], reverse_ratio=1)
results = temporal_reverse(results)
assert self.check_keys_contain(results.keys(), target_keys)
np.testing.assert_almost_equal(results['lq'][0], img_lq2)
np.testing.assert_almost_equal(results['lq'][1], img_lq1)
np.testing.assert_almost_equal(results['gt'][0], img_gt)
assert repr(
temporal_reverse) == temporal_reverse.__class__.__name__ + (
f"(keys={['lq', 'gt']}, reverse_ratio=1)")
results = dict(lq=[img_lq1, img_lq2], gt=[img_gt])
temporal_reverse = TemporalReverse(keys=['lq', 'gt'], reverse_ratio=0)
results = temporal_reverse(results)
assert self.check_keys_contain(results.keys(), target_keys)
np.testing.assert_almost_equal(results['lq'][0], img_lq1)
np.testing.assert_almost_equal(results['lq'][1], img_lq2)
np.testing.assert_almost_equal(results['gt'][0], img_gt)
def test_frame_index_generation_for_recurrent(self):
results = dict(
lq_path='fake_lq_root',
gt_path='fake_gt_root',
key='000',
num_input_frames=10,
sequence_length=100)
target_keys = [
'lq_path', 'gt_path', 'key', 'interval', 'num_input_frames',
'sequence_length'
]
frame_index_generator = GenerateSegmentIndices(interval_list=[1, 5, 9])
rlt = frame_index_generator(copy.deepcopy(results))
assert self.check_keys_contain(rlt.keys(), target_keys)
name_ = repr(frame_index_generator)
assert name_ == frame_index_generator.__class__.__name__ + (
'(interval_list=[1, 5, 9])')
# interval too large
results = dict(
lq_path='fake_lq_root',
gt_path='fake_gt_root',
key='000',
num_input_frames=11,
sequence_length=100)
frame_index_generator = GenerateSegmentIndices(interval_list=[10])
with pytest.raises(ValueError):
frame_index_generator(copy.deepcopy(results))
def test_mirror_sequence(self):
lqs = [np.random.rand(4, 4, 3) for _ in range(0, 5)]
gts = [np.random.rand(16, 16, 3) for _ in range(0, 5)]
target_keys = ['lq', 'gt']
mirror_sequence = MirrorSequence(keys=['lq', 'gt'])
results = dict(lq=lqs, gt=gts)
results = mirror_sequence(results)
assert self.check_keys_contain(results.keys(), target_keys)
for i in range(0, 5):
np.testing.assert_almost_equal(results['lq'][i],
results['lq'][-i - 1])
np.testing.assert_almost_equal(results['gt'][i],
results['gt'][-i - 1])
assert repr(mirror_sequence) == mirror_sequence.__class__.__name__ + (
"(keys=['lq', 'gt'])")
# each key should contain a list of nparray
with pytest.raises(TypeError):
results = dict(lq=0, gt=gts)
mirror_sequence(results)
def test_quantize(self):
results = {}
# clip (>1)
results['gt'] = 1.1 * np.ones((1, 1, 3)).astype(np.float32)
model = Quantize(keys=['gt'])
assert np.array_equal(
model(results)['gt'],
np.ones((1, 1, 3)).astype(np.float32))
# clip (<0)
results['gt'] = -0.1 * np.ones((1, 1, 3)).astype(np.float32)
model = Quantize(keys=['gt'])
assert np.array_equal(
model(results)['gt'],
np.zeros((1, 1, 3)).astype(np.float32))
# round
results['gt'] = (1 / 255. + 1e-8) * np.ones(
(1, 1, 3)).astype(np.float32)
model = Quantize(keys=['gt'])
assert np.array_equal(
model(results)['gt'], (1 / 255.) * np.ones(
(1, 1, 3)).astype(np.float32))
def test_copy_value(self):
with pytest.raises(AssertionError):
CopyValues(src_keys='gt', dst_keys='lq')
with pytest.raises(ValueError):
CopyValues(src_keys=['gt', 'mask'], dst_keys=['lq'])
results = {}
results['gt'] = np.zeros((1)).astype(np.float32)
copy_ = CopyValues(src_keys=['gt'], dst_keys=['lq'])
assert np.array_equal(copy_(results)['lq'], results['gt'])
assert repr(copy_) == copy_.__class__.__name__ + (
f"(src_keys=['gt'])"
f"(dst_keys=['lq'])")
def test_unsharp_masking(self):
results = {}
unsharp_masking = UnsharpMasking(
kernel_size=15, sigma=0, weight=0.5, threshold=10, keys=['gt'])
# single image
results['gt'] = np.zeros((8, 8, 3)).astype(np.float32)
results = unsharp_masking(results)
assert isinstance(results['gt_unsharp'], np.ndarray)
# sequence of images
results['gt'] = [np.zeros((8, 8, 3)).astype(np.float32)] * 2
results = unsharp_masking(results)
assert isinstance(results['gt_unsharp'], list)
assert repr(unsharp_masking) == unsharp_masking.__class__.__name__ + (
"(keys=['gt'], kernel_size=15, sigma=0, weight=0.5, threshold=10)")
# kernel_size must be odd
with pytest.raises(ValueError):
unsharp_masking = UnsharpMasking(
kernel_size=10, sigma=0, weight=0.5, threshold=10, keys=['gt'])
| 35,573 | 41.860241 | 79 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_utils/test_tensor2img.py | # Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
import pytest
import torch
from torchvision.utils import make_grid
from mmedit.core import tensor2img
def test_tensor2img():
tensor_4d_1 = torch.FloatTensor(2, 3, 4, 4).uniform_(0, 1)
tensor_4d_2 = torch.FloatTensor(1, 3, 4, 4).uniform_(0, 1)
tensor_4d_3 = torch.FloatTensor(3, 1, 4, 4).uniform_(0, 1)
tensor_4d_4 = torch.FloatTensor(1, 1, 4, 4).uniform_(0, 1)
tensor_3d_1 = torch.FloatTensor(3, 4, 4).uniform_(0, 1)
tensor_3d_2 = torch.FloatTensor(3, 6, 6).uniform_(0, 1)
tensor_3d_3 = torch.FloatTensor(1, 6, 6).uniform_(0, 1)
tensor_2d = torch.FloatTensor(4, 4).uniform_(0, 1)
with pytest.raises(TypeError):
# input is not a tensor
tensor2img(4)
with pytest.raises(TypeError):
# input is not a list of tensors
tensor2img([tensor_3d_1, 4])
with pytest.raises(ValueError):
# unsupported 5D tensor
tensor2img(torch.FloatTensor(2, 2, 3, 4, 4).uniform_(0, 1))
# 4d
rlt = tensor2img(tensor_4d_1, out_type=np.uint8, min_max=(0, 1))
assert rlt.dtype == np.uint8
tensor_4d_1_np = make_grid(tensor_4d_1, nrow=1, normalize=False).numpy()
tensor_4d_1_np = np.transpose(tensor_4d_1_np[[2, 1, 0], :, :], (1, 2, 0))
np.testing.assert_almost_equal(rlt, (tensor_4d_1_np * 255).round())
rlt = tensor2img(tensor_4d_2, out_type=np.uint8, min_max=(0, 1))
assert rlt.dtype == np.uint8
tensor_4d_2_np = tensor_4d_2.squeeze().numpy()
tensor_4d_2_np = np.transpose(tensor_4d_2_np[[2, 1, 0], :, :], (1, 2, 0))
np.testing.assert_almost_equal(rlt, (tensor_4d_2_np * 255).round())
rlt = tensor2img(tensor_4d_3, out_type=np.uint8, min_max=(0, 1))
assert rlt.dtype == np.uint8
tensor_4d_3_np = make_grid(tensor_4d_3, nrow=1, normalize=False).numpy()
tensor_4d_3_np = np.transpose(tensor_4d_3_np[[2, 1, 0], :, :], (1, 2, 0))
np.testing.assert_almost_equal(rlt, (tensor_4d_3_np * 255).round())
rlt = tensor2img(tensor_4d_4, out_type=np.uint8, min_max=(0, 1))
assert rlt.dtype == np.uint8
tensor_4d_4_np = tensor_4d_4.squeeze().numpy()
np.testing.assert_almost_equal(rlt, (tensor_4d_4_np * 255).round())
# 3d
rlt = tensor2img([tensor_3d_1, tensor_3d_2],
out_type=np.uint8,
min_max=(0, 1))
assert rlt[0].dtype == np.uint8
tensor_3d_1_np = tensor_3d_1.numpy()
tensor_3d_1_np = np.transpose(tensor_3d_1_np[[2, 1, 0], :, :], (1, 2, 0))
tensor_3d_2_np = tensor_3d_2.numpy()
tensor_3d_2_np = np.transpose(tensor_3d_2_np[[2, 1, 0], :, :], (1, 2, 0))
np.testing.assert_almost_equal(rlt[0], (tensor_3d_1_np * 255).round())
np.testing.assert_almost_equal(rlt[1], (tensor_3d_2_np * 255).round())
rlt = tensor2img(tensor_3d_3, out_type=np.uint8, min_max=(0, 1))
assert rlt.dtype == np.uint8
tensor_3d_3_np = tensor_3d_3.squeeze().numpy()
np.testing.assert_almost_equal(rlt, (tensor_3d_3_np * 255).round())
# 2d
rlt = tensor2img(tensor_2d, out_type=np.uint8, min_max=(0, 1))
assert rlt.dtype == np.uint8
tensor_2d_np = tensor_2d.numpy()
np.testing.assert_almost_equal(rlt, (tensor_2d_np * 255).round())
rlt = tensor2img(tensor_2d, out_type=np.float32, min_max=(0, 1))
assert rlt.dtype == np.float32
np.testing.assert_almost_equal(rlt, tensor_2d_np)
rlt = tensor2img(tensor_2d, out_type=np.float32, min_max=(0.1, 0.5))
assert rlt.dtype == np.float32
tensor_2d_np = (np.clip(tensor_2d_np, 0.1, 0.5) - 0.1) / 0.4
np.testing.assert_almost_equal(rlt, tensor_2d_np)
| 3,609 | 41.97619 | 77 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_utils/test_pix2pix.py | # Copyright (c) OpenMMLab. All rights reserved.
import copy
from unittest.mock import patch
import mmcv
import pytest
import torch
from mmcv.parallel import DataContainer as DC
from mmcv.runner import obj_from_dict
from mmedit.models import build_model
from mmedit.models.backbones import UnetGenerator
from mmedit.models.components import PatchDiscriminator
from mmedit.models.losses import GANLoss, L1Loss
def test_pix2pix():
model_cfg = dict(
type='Pix2Pix',
generator=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)),
discriminator=dict(
type='PatchDiscriminator',
in_channels=6,
base_channels=64,
num_conv=3,
norm_cfg=dict(type='BN'),
init_cfg=dict(type='normal', gain=0.02)),
gan_loss=dict(
type='GANLoss',
gan_type='vanilla',
real_label_val=1.0,
fake_label_val=0,
loss_weight=1.0),
pixel_loss=dict(type='L1Loss', loss_weight=100.0, reduction='mean'))
train_cfg = None
test_cfg = None
# build synthesizer
synthesizer = build_model(
model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
# test checking gan loss cannot be None
with pytest.raises(AssertionError):
bad_model_cfg = copy.deepcopy(model_cfg)
bad_model_cfg['gan_loss'] = None
_ = build_model(bad_model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
# test attributes
assert synthesizer.__class__.__name__ == 'Pix2Pix'
assert isinstance(synthesizer.generator, UnetGenerator)
assert isinstance(synthesizer.discriminator, PatchDiscriminator)
assert isinstance(synthesizer.gan_loss, GANLoss)
assert isinstance(synthesizer.pixel_loss, L1Loss)
assert synthesizer.train_cfg is None
assert synthesizer.test_cfg is None
# prepare data
inputs = torch.rand(1, 3, 256, 256)
targets = torch.rand(1, 3, 256, 256)
data_batch = {'img_a': inputs, 'img_b': targets}
img_meta = {}
img_meta['img_a_path'] = 'img_a_path'
img_meta['img_b_path'] = 'img_b_path'
data_batch['meta'] = [img_meta]
# prepare optimizer
optim_cfg = dict(type='Adam', lr=2e-4, betas=(0.5, 0.999))
optimizer = {
'generator':
obj_from_dict(
optim_cfg, torch.optim,
dict(params=getattr(synthesizer, 'generator').parameters())),
'discriminator':
obj_from_dict(
optim_cfg, torch.optim,
dict(params=getattr(synthesizer, 'discriminator').parameters()))
}
# test forward_dummy
with torch.no_grad():
output = synthesizer.forward_dummy(data_batch['img_a'])
assert torch.is_tensor(output)
assert output.size() == (1, 3, 256, 256)
# test forward_test
with torch.no_grad():
outputs = synthesizer(inputs, targets, [img_meta], test_mode=True)
assert torch.equal(outputs['real_a'], data_batch['img_a'])
assert torch.equal(outputs['real_b'], data_batch['img_b'])
assert torch.is_tensor(outputs['fake_b'])
assert outputs['fake_b'].size() == (1, 3, 256, 256)
# val_step
with torch.no_grad():
outputs = synthesizer.val_step(data_batch)
assert torch.equal(outputs['real_a'], data_batch['img_a'])
assert torch.equal(outputs['real_b'], data_batch['img_b'])
assert torch.is_tensor(outputs['fake_b'])
assert outputs['fake_b'].size() == (1, 3, 256, 256)
# test forward_train
outputs = synthesizer(inputs, targets, [img_meta], test_mode=False)
assert torch.equal(outputs['real_a'], data_batch['img_a'])
assert torch.equal(outputs['real_b'], data_batch['img_b'])
assert torch.is_tensor(outputs['fake_b'])
assert outputs['fake_b'].size() == (1, 3, 256, 256)
# test train_step
outputs = synthesizer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
assert isinstance(outputs['results'], dict)
for v in [
'loss_gan_d_fake', 'loss_gan_d_real', 'loss_gan_g', 'loss_pixel'
]:
assert isinstance(outputs['log_vars'][v], float)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['real_a'], data_batch['img_a'])
assert torch.equal(outputs['results']['real_b'], data_batch['img_b'])
assert torch.is_tensor(outputs['results']['fake_b'])
assert outputs['results']['fake_b'].size() == (1, 3, 256, 256)
# test train_step and forward_test (gpu)
if torch.cuda.is_available():
synthesizer = synthesizer.cuda()
optimizer = {
'generator':
obj_from_dict(
optim_cfg, torch.optim,
dict(params=getattr(synthesizer, 'generator').parameters())),
'discriminator':
obj_from_dict(
optim_cfg, torch.optim,
dict(
params=getattr(synthesizer, 'discriminator').parameters()))
}
data_batch_cuda = copy.deepcopy(data_batch)
data_batch_cuda['img_a'] = inputs.cuda()
data_batch_cuda['img_b'] = targets.cuda()
data_batch_cuda['meta'] = [DC(img_meta, cpu_only=True).data]
# forward_test
with torch.no_grad():
outputs = synthesizer(
data_batch_cuda['img_a'],
data_batch_cuda['img_b'],
data_batch_cuda['meta'],
test_mode=True)
assert torch.equal(outputs['real_a'], data_batch_cuda['img_a'].cpu())
assert torch.equal(outputs['real_b'], data_batch_cuda['img_b'].cpu())
assert torch.is_tensor(outputs['fake_b'])
assert outputs['fake_b'].size() == (1, 3, 256, 256)
# val_step
with torch.no_grad():
outputs = synthesizer.val_step(data_batch_cuda)
assert torch.equal(outputs['real_a'], data_batch_cuda['img_a'].cpu())
assert torch.equal(outputs['real_b'], data_batch_cuda['img_b'].cpu())
assert torch.is_tensor(outputs['fake_b'])
assert outputs['fake_b'].size() == (1, 3, 256, 256)
# test forward_train
outputs = synthesizer(
data_batch_cuda['img_a'],
data_batch_cuda['img_b'],
data_batch_cuda['meta'],
test_mode=False)
assert torch.equal(outputs['real_a'], data_batch_cuda['img_a'])
assert torch.equal(outputs['real_b'], data_batch_cuda['img_b'])
assert torch.is_tensor(outputs['fake_b'])
assert outputs['fake_b'].size() == (1, 3, 256, 256)
# train_step
outputs = synthesizer.train_step(data_batch_cuda, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
assert isinstance(outputs['results'], dict)
for v in [
'loss_gan_d_fake', 'loss_gan_d_real', 'loss_gan_g',
'loss_pixel'
]:
assert isinstance(outputs['log_vars'][v], float)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['real_a'],
data_batch_cuda['img_a'].cpu())
assert torch.equal(outputs['results']['real_b'],
data_batch_cuda['img_b'].cpu())
assert torch.is_tensor(outputs['results']['fake_b'])
assert outputs['results']['fake_b'].size() == (1, 3, 256, 256)
# test disc_steps and disc_init_steps
data_batch['img_a'] = inputs.cpu()
data_batch['img_b'] = targets.cpu()
train_cfg = dict(disc_steps=2, disc_init_steps=2)
synthesizer = build_model(
model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
optimizer = {
'generator':
obj_from_dict(
optim_cfg, torch.optim,
dict(params=getattr(synthesizer, 'generator').parameters())),
'discriminator':
obj_from_dict(
optim_cfg, torch.optim,
dict(params=getattr(synthesizer, 'discriminator').parameters()))
}
# iter 0, 1
for i in range(2):
assert synthesizer.step_counter == i
outputs = synthesizer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
assert isinstance(outputs['results'], dict)
assert outputs['log_vars'].get('loss_gan_g') is None
assert outputs['log_vars'].get('loss_pixel') is None
for v in ['loss_gan_d_fake', 'loss_gan_d_real']:
assert isinstance(outputs['log_vars'][v], float)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['real_a'], data_batch['img_a'])
assert torch.equal(outputs['results']['real_b'], data_batch['img_b'])
assert torch.is_tensor(outputs['results']['fake_b'])
assert outputs['results']['fake_b'].size() == (1, 3, 256, 256)
assert synthesizer.step_counter == i + 1
# iter 2, 3, 4, 5
for i in range(2, 6):
assert synthesizer.step_counter == i
outputs = synthesizer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
assert isinstance(outputs['results'], dict)
log_check_list = [
'loss_gan_d_fake', 'loss_gan_d_real', 'loss_gan_g', 'loss_pixel'
]
if i % 2 == 1:
assert outputs['log_vars'].get('loss_gan_g') is None
assert outputs['log_vars'].get('loss_pixel') is None
log_check_list.remove('loss_gan_g')
log_check_list.remove('loss_pixel')
for v in log_check_list:
assert isinstance(outputs['log_vars'][v], float)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['real_a'], data_batch['img_a'])
assert torch.equal(outputs['results']['real_b'], data_batch['img_b'])
assert torch.is_tensor(outputs['results']['fake_b'])
assert outputs['results']['fake_b'].size() == (1, 3, 256, 256)
assert synthesizer.step_counter == i + 1
# test without pixel loss
model_cfg_ = copy.deepcopy(model_cfg)
model_cfg_.pop('pixel_loss')
synthesizer = build_model(model_cfg_, train_cfg=None, test_cfg=None)
optimizer = {
'generator':
obj_from_dict(
optim_cfg, torch.optim,
dict(params=getattr(synthesizer, 'generator').parameters())),
'discriminator':
obj_from_dict(
optim_cfg, torch.optim,
dict(params=getattr(synthesizer, 'discriminator').parameters()))
}
data_batch['img_a'] = inputs.cpu()
data_batch['img_b'] = targets.cpu()
outputs = synthesizer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
assert isinstance(outputs['results'], dict)
assert outputs['log_vars'].get('loss_pixel') is None
for v in ['loss_gan_d_fake', 'loss_gan_d_real', 'loss_gan_g']:
assert isinstance(outputs['log_vars'][v], float)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['real_a'], data_batch['img_a'])
assert torch.equal(outputs['results']['real_b'], data_batch['img_b'])
assert torch.is_tensor(outputs['results']['fake_b'])
assert outputs['results']['fake_b'].size() == (1, 3, 256, 256)
# test b2a translation
data_batch['img_a'] = inputs.cpu()
data_batch['img_b'] = targets.cpu()
train_cfg = dict(direction='b2a')
synthesizer = build_model(
model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
optimizer = {
'generator':
obj_from_dict(
optim_cfg, torch.optim,
dict(params=getattr(synthesizer, 'generator').parameters())),
'discriminator':
obj_from_dict(
optim_cfg, torch.optim,
dict(params=getattr(synthesizer, 'discriminator').parameters()))
}
assert synthesizer.step_counter == 0
outputs = synthesizer.train_step(data_batch, optimizer)
assert isinstance(outputs, dict)
assert isinstance(outputs['log_vars'], dict)
assert isinstance(outputs['results'], dict)
for v in [
'loss_gan_d_fake', 'loss_gan_d_real', 'loss_gan_g', 'loss_pixel'
]:
assert isinstance(outputs['log_vars'][v], float)
assert outputs['num_samples'] == 1
assert torch.equal(outputs['results']['real_a'], data_batch['img_b'])
assert torch.equal(outputs['results']['real_b'], data_batch['img_a'])
assert torch.is_tensor(outputs['results']['fake_b'])
assert outputs['results']['fake_b'].size() == (1, 3, 256, 256)
assert synthesizer.step_counter == 1
# test save image
# show input
train_cfg = None
test_cfg = dict(show_input=True)
synthesizer = build_model(
model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
with patch.object(mmcv, 'imwrite', return_value=True):
# test save path not None Assertion
with pytest.raises(AssertionError):
with torch.no_grad():
_ = synthesizer(
inputs,
targets, [img_meta],
test_mode=True,
save_image=True)
# iteration is None
with torch.no_grad():
outputs = synthesizer(
inputs,
targets, [img_meta],
test_mode=True,
save_image=True,
save_path='save_path')
assert torch.equal(outputs['real_a'], data_batch['img_a'])
assert torch.equal(outputs['real_b'], data_batch['img_b'])
assert torch.is_tensor(outputs['fake_b'])
assert outputs['fake_b'].size() == (1, 3, 256, 256)
assert outputs['saved_flag']
# iteration is not None
with torch.no_grad():
outputs = synthesizer(
inputs,
targets, [img_meta],
test_mode=True,
save_image=True,
save_path='save_path',
iteration=1000)
assert torch.equal(outputs['real_a'], data_batch['img_a'])
assert torch.equal(outputs['real_b'], data_batch['img_b'])
assert torch.is_tensor(outputs['fake_b'])
assert outputs['fake_b'].size() == (1, 3, 256, 256)
assert outputs['saved_flag']
# not show input
train_cfg = None
test_cfg = dict(show_input=False)
synthesizer = build_model(
model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)
with patch.object(mmcv, 'imwrite', return_value=True):
# test save path not None Assertion
with pytest.raises(AssertionError):
with torch.no_grad():
_ = synthesizer(
inputs,
targets, [img_meta],
test_mode=True,
save_image=True)
# iteration is None
with torch.no_grad():
outputs = synthesizer(
inputs,
targets, [img_meta],
test_mode=True,
save_image=True,
save_path='save_path')
assert torch.equal(outputs['real_a'], data_batch['img_a'])
assert torch.equal(outputs['real_b'], data_batch['img_b'])
assert torch.is_tensor(outputs['fake_b'])
assert outputs['fake_b'].size() == (1, 3, 256, 256)
assert outputs['saved_flag']
# iteration is not None
with torch.no_grad():
outputs = synthesizer(
inputs,
targets, [img_meta],
test_mode=True,
save_image=True,
save_path='save_path',
iteration=1000)
assert torch.equal(outputs['real_a'], data_batch['img_a'])
assert torch.equal(outputs['real_b'], data_batch['img_b'])
assert torch.is_tensor(outputs['fake_b'])
assert outputs['fake_b'].size() == (1, 3, 256, 256)
assert outputs['saved_flag']
| 16,144 | 38.864198 | 79 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/tests/test_utils/test_onnx_wraper.py | # Copyright (c) OpenMMLab. All rights reserved.
import os
import mmcv
import numpy as np
import pytest
import torch
from packaging import version
from mmedit.models import build_model
@pytest.mark.skipif(torch.__version__ == 'parrots', reason='skip parrots.')
@pytest.mark.skipif(
version.parse(torch.__version__) < version.parse('1.4.0'),
reason='skip if torch=1.3.x')
def test_restorer_wrapper():
try:
import onnxruntime as ort
from mmedit.core.export.wrappers import (ONNXRuntimeEditing,
ONNXRuntimeRestorer)
except ImportError:
pytest.skip('ONNXRuntime is not available.')
onnx_path = 'tmp.onnx'
scale = 4
train_cfg = None
test_cfg = None
cfg = dict(
model=dict(
type='BasicRestorer',
generator=dict(
type='SRCNN',
channels=(3, 4, 2, 3),
kernel_sizes=(9, 1, 5),
upscale_factor=scale),
pixel_loss=dict(type='L1Loss', loss_weight=1.0, reduction='mean')),
train_cfg=train_cfg,
test_cfg=test_cfg)
cfg = mmcv.Config(cfg)
pytorch_model = build_model(
cfg.model, train_cfg=cfg.train_cfg, test_cfg=cfg.test_cfg)
# prepare data
inputs = torch.rand(1, 3, 2, 2)
targets = torch.rand(1, 3, 8, 8)
data_batch = {'lq': inputs, 'gt': targets}
pytorch_model.forward = pytorch_model.forward_dummy
with torch.no_grad():
torch.onnx.export(
pytorch_model,
inputs,
onnx_path,
input_names=['input'],
output_names=['output'],
export_params=True,
keep_initializers_as_inputs=False,
verbose=False,
opset_version=11)
wrap_model = ONNXRuntimeEditing(onnx_path, cfg, 0)
# os.remove(onnx_path)
assert isinstance(wrap_model.wrapper, ONNXRuntimeRestorer)
if ort.get_device() == 'GPU':
data_batch = {'lq': inputs.cuda(), 'gt': targets.cuda()}
with torch.no_grad():
outputs = wrap_model(**data_batch, test_mode=True)
assert isinstance(outputs, dict)
assert 'output' in outputs
output = outputs['output']
assert isinstance(output, torch.Tensor)
assert output.shape == targets.shape
@pytest.mark.skipif(torch.__version__ == 'parrots', reason='skip parrots.')
@pytest.mark.skipif(
version.parse(torch.__version__) < version.parse('1.4.0'),
reason='skip if torch=1.3.x')
def test_mattor_wrapper():
try:
import onnxruntime as ort
from mmedit.core.export.wrappers import (ONNXRuntimeEditing,
ONNXRuntimeMattor)
except ImportError:
pytest.skip('ONNXRuntime is not available.')
onnx_path = 'tmp.onnx'
train_cfg = None
test_cfg = dict(refine=False, metrics=['SAD', 'MSE', 'GRAD', 'CONN'])
cfg = dict(
model=dict(
type='DIM',
backbone=dict(
type='SimpleEncoderDecoder',
encoder=dict(type='VGG16', in_channels=4),
decoder=dict(type='PlainDecoder')),
pretrained='open-mmlab://mmedit/vgg16',
loss_alpha=dict(type='CharbonnierLoss', loss_weight=0.5),
loss_comp=dict(type='CharbonnierCompLoss', loss_weight=0.5)),
train_cfg=train_cfg,
test_cfg=test_cfg)
cfg = mmcv.Config(cfg)
pytorch_model = build_model(
cfg.model, train_cfg=cfg.train_cfg, test_cfg=cfg.test_cfg)
img_shape = (32, 32)
merged = torch.rand(1, 3, img_shape[1], img_shape[0])
trimap = torch.rand(1, 1, img_shape[1], img_shape[0])
data_batch = {'merged': merged, 'trimap': trimap}
inputs = torch.cat([merged, trimap], dim=1)
pytorch_model.forward = pytorch_model.forward_dummy
with torch.no_grad():
torch.onnx.export(
pytorch_model,
inputs,
onnx_path,
input_names=['input'],
output_names=['output'],
export_params=True,
keep_initializers_as_inputs=False,
verbose=False,
opset_version=11)
wrap_model = ONNXRuntimeEditing(onnx_path, cfg, 0)
os.remove(onnx_path)
assert isinstance(wrap_model.wrapper, ONNXRuntimeMattor)
if ort.get_device() == 'GPU':
merged = merged.cuda()
trimap = trimap.cuda()
data_batch = {'merged': merged, 'trimap': trimap}
ori_alpha = np.random.random(img_shape).astype(np.float32)
ori_trimap = np.random.randint(256, size=img_shape).astype(np.float32)
data_batch['meta'] = [
dict(
ori_alpha=ori_alpha,
ori_trimap=ori_trimap,
merged_ori_shape=img_shape)
]
with torch.no_grad():
outputs = wrap_model(**data_batch, test_mode=True)
assert isinstance(outputs, dict)
assert 'pred_alpha' in outputs
pred_alpha = outputs['pred_alpha']
assert isinstance(pred_alpha, np.ndarray)
assert pred_alpha.shape == img_shape
| 5,043 | 30.924051 | 79 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/demo/restoration_video_demo.py | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import os
import cv2
import mmcv
import numpy as np
import torch
from mmedit.apis import init_model, restoration_video_inference
from mmedit.core import tensor2img
from mmedit.utils import modify_args
VIDEO_EXTENSIONS = ('.mp4', '.mov')
def parse_args():
modify_args()
parser = argparse.ArgumentParser(description='Restoration demo')
parser.add_argument('config', help='test config file path')
parser.add_argument('checkpoint', help='checkpoint file')
parser.add_argument('input_dir', help='directory of the input video')
parser.add_argument('output_dir', help='directory of the output video')
parser.add_argument(
'--start-idx',
type=int,
default=0,
help='index corresponds to the first frame of the sequence')
parser.add_argument(
'--filename-tmpl',
default='{:08d}.png',
help='template of the file names')
parser.add_argument(
'--window-size',
type=int,
default=0,
help='window size if sliding-window framework is used')
parser.add_argument(
'--max-seq-len',
type=int,
default=None,
help='maximum sequence length if recurrent framework is used')
parser.add_argument('--device', type=int, default=0, help='CUDA device id')
args = parser.parse_args()
return args
def main():
""" Demo for video restoration models.
Note that we accept video as input/output, when 'input_dir'/'output_dir'
is set to the path to the video. But using videos introduces video
compression, which lowers the visual quality. If you want actual quality,
please save them as separate images (.png).
"""
args = parse_args()
model = init_model(
args.config, args.checkpoint, device=torch.device('cuda', args.device))
output = restoration_video_inference(model, args.input_dir,
args.window_size, args.start_idx,
args.filename_tmpl, args.max_seq_len)
file_extension = os.path.splitext(args.output_dir)[1]
if file_extension in VIDEO_EXTENSIONS: # save as video
h, w = output.shape[-2:]
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
video_writer = cv2.VideoWriter(args.output_dir, fourcc, 25, (w, h))
for i in range(0, output.size(1)):
img = tensor2img(output[:, i, :, :, :])
video_writer.write(img.astype(np.uint8))
cv2.destroyAllWindows()
video_writer.release()
else:
for i in range(args.start_idx, args.start_idx + output.size(1)):
output_i = output[:, i - args.start_idx, :, :, :]
output_i = tensor2img(output_i)
save_path_i = f'{args.output_dir}/{args.filename_tmpl.format(i)}'
mmcv.imwrite(output_i, save_path_i)
if __name__ == '__main__':
main()
| 2,938 | 32.781609 | 79 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/mmedit/apis/test.py | # Copyright (c) OpenMMLab. All rights reserved.
import os.path as osp
import pickle
import shutil
import tempfile
import mmcv
import torch
import torch.distributed as dist
from mmcv.runner import get_dist_info
def single_gpu_test(model,
data_loader,
save_image=False,
save_path=None,
iteration=None):
"""Test model with a single gpu.
This method tests model with a single gpu and displays test progress bar.
Args:
model (nn.Module): Model to be tested.
data_loader (nn.Dataloader): Pytorch data loader.
save_image (bool): Whether save image. Default: False.
save_path (str): The path to save image. Default: None.
iteration (int): Iteration number. It is used for the save image name.
Default: None.
Returns:
list: The prediction results.
"""
if save_image and save_path is None:
raise ValueError(
"When 'save_image' is True, you should also set 'save_path'.")
model.eval()
results = []
dataset = data_loader.dataset
prog_bar = mmcv.ProgressBar(len(dataset))
for data in data_loader:
with torch.no_grad():
result = model(
test_mode=True,
save_image=save_image,
save_path=save_path,
iteration=iteration,
**data)
results.append(result)
# get batch size
for _, v in data.items():
if isinstance(v, torch.Tensor):
batch_size = v.size(0)
break
for _ in range(batch_size):
prog_bar.update()
return results
def multi_gpu_test(model,
data_loader,
tmpdir=None,
gpu_collect=False,
save_image=False,
save_path=None,
iteration=None,
empty_cache=False):
"""Test model with multiple gpus.
This method tests model with multiple gpus and collects the results
under two different modes: gpu and cpu modes. By setting 'gpu_collect=True'
it encodes results to gpu tensors and use gpu communication for results
collection. On cpu mode it saves the results on different gpus to 'tmpdir'
and collects them by the rank 0 worker.
Args:
model (nn.Module): Model to be tested.
data_loader (nn.Dataloader): Pytorch data loader.
tmpdir (str): Path of directory to save the temporary results from
different gpus under cpu mode.
gpu_collect (bool): Option to use either gpu or cpu to collect results.
save_image (bool): Whether save image. Default: False.
save_path (str): The path to save image. Default: None.
iteration (int): Iteration number. It is used for the save image name.
Default: None.
empty_cache (bool): empty cache in every iteration. Default: False.
Returns:
list: The prediction results.
"""
if save_image and save_path is None:
raise ValueError(
"When 'save_image' is True, you should also set 'save_path'.")
model.eval()
results = []
dataset = data_loader.dataset
rank, world_size = get_dist_info()
if rank == 0:
prog_bar = mmcv.ProgressBar(len(dataset))
for data in data_loader:
with torch.no_grad():
result = model(
test_mode=True,
save_image=save_image,
save_path=save_path,
iteration=iteration,
**data)
results.append(result)
if empty_cache:
torch.cuda.empty_cache()
if rank == 0:
# get batch size
for _, v in data.items():
if isinstance(v, torch.Tensor):
batch_size = v.size(0)
break
for _ in range(batch_size * world_size):
prog_bar.update()
# collect results from all ranks
if gpu_collect:
results = collect_results_gpu(results, len(dataset))
else:
results = collect_results_cpu(results, len(dataset), tmpdir)
return results
def collect_results_cpu(result_part, size, tmpdir=None):
"""Collect results in cpu mode.
It saves the results on different gpus to 'tmpdir' and collects
them by the rank 0 worker.
Args:
result_part (list): Results to be collected
size (int): Result size.
tmpdir (str): Path of directory to save the temporary results from
different gpus under cpu mode. Default: None
Returns:
list: Ordered results.
"""
rank, world_size = get_dist_info()
# create a tmp dir if it is not specified
if tmpdir is None:
MAX_LEN = 512
# 32 is whitespace
dir_tensor = torch.full((MAX_LEN, ),
32,
dtype=torch.uint8,
device='cuda')
if rank == 0:
mmcv.mkdir_or_exist('.dist_test')
tmpdir = tempfile.mkdtemp(dir='.dist_test')
tmpdir = torch.tensor(
bytearray(tmpdir.encode()), dtype=torch.uint8, device='cuda')
dir_tensor[:len(tmpdir)] = tmpdir
dist.broadcast(dir_tensor, 0)
tmpdir = dir_tensor.cpu().numpy().tobytes().decode().rstrip()
else:
mmcv.mkdir_or_exist(tmpdir)
# synchronizes all processes to make sure tmpdir exist
dist.barrier()
# dump the part result to the dir
mmcv.dump(result_part, osp.join(tmpdir, 'part_{}.pkl'.format(rank)))
# synchronizes all processes for loading pickle file
dist.barrier()
# collect all parts
if rank != 0:
return None
# load results of all parts from tmp dir
part_list = []
for i in range(world_size):
part_file = osp.join(tmpdir, 'part_{}.pkl'.format(i))
part_list.append(mmcv.load(part_file))
# sort the results
ordered_results = []
for res in zip(*part_list):
ordered_results.extend(list(res))
# the dataloader may pad some samples
ordered_results = ordered_results[:size]
# remove tmp dir
shutil.rmtree(tmpdir)
return ordered_results
def collect_results_gpu(result_part, size):
"""Collect results in gpu mode.
It encodes results to gpu tensors and use gpu communication for results
collection.
Args:
result_part (list): Results to be collected
size (int): Result size.
Returns:
list: Ordered results.
"""
rank, world_size = get_dist_info()
# dump result part to tensor with pickle
part_tensor = torch.tensor(
bytearray(pickle.dumps(result_part)), dtype=torch.uint8, device='cuda')
# gather all result part tensor shape
shape_tensor = torch.tensor(part_tensor.shape, device='cuda')
shape_list = [shape_tensor.clone() for _ in range(world_size)]
dist.all_gather(shape_list, shape_tensor)
# padding result part tensor to max length
shape_max = torch.tensor(shape_list).max()
part_send = torch.zeros(shape_max, dtype=torch.uint8, device='cuda')
part_send[:shape_tensor[0]] = part_tensor
part_recv_list = [
part_tensor.new_zeros(shape_max) for _ in range(world_size)
]
# gather all result part
dist.all_gather(part_recv_list, part_send)
if rank != 0:
return None
part_list = []
for recv, shape in zip(part_recv_list, shape_list):
part_list.append(pickle.loads(recv[:shape[0]].cpu().numpy().tobytes()))
# sort the results
ordered_results = []
for res in zip(*part_list):
ordered_results.extend(list(res))
# the dataloader may pad some samples
ordered_results = ordered_results[:size]
return ordered_results
| 7,852 | 32.417021 | 79 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/mmedit/apis/restoration_face_inference.py | # Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
import torch
from mmcv.parallel import collate, scatter
from mmedit.datasets.pipelines import Compose
try:
from facexlib.utils.face_restoration_helper import FaceRestoreHelper
has_facexlib = True
except ImportError:
has_facexlib = False
def restoration_face_inference(model, img, upscale_factor=1, face_size=1024):
"""Inference image with the model.
Args:
model (nn.Module): The loaded model.
img (str): File path of input image.
upscale_factor (int, optional): The number of times the input image
is upsampled. Default: 1.
face_size (int, optional): The size of the cropped and aligned faces.
Default: 1024.
Returns:
Tensor: The predicted restoration result.
"""
device = next(model.parameters()).device # model device
# build the data pipeline
if model.cfg.get('demo_pipeline', None):
test_pipeline = model.cfg.demo_pipeline
elif model.cfg.get('test_pipeline', None):
test_pipeline = model.cfg.test_pipeline
else:
test_pipeline = model.cfg.val_pipeline
# remove gt from test_pipeline
keys_to_remove = ['gt', 'gt_path']
for key in keys_to_remove:
for pipeline in list(test_pipeline):
if 'key' in pipeline and key == pipeline['key']:
test_pipeline.remove(pipeline)
if 'keys' in pipeline and key in pipeline['keys']:
pipeline['keys'].remove(key)
if len(pipeline['keys']) == 0:
test_pipeline.remove(pipeline)
if 'meta_keys' in pipeline and key in pipeline['meta_keys']:
pipeline['meta_keys'].remove(key)
# build the data pipeline
test_pipeline = Compose(test_pipeline)
# face helper for detecting and aligning faces
assert has_facexlib, 'Please install FaceXLib to use the demo.'
face_helper = FaceRestoreHelper(
upscale_factor,
face_size=face_size,
crop_ratio=(1, 1),
det_model='retinaface_resnet50',
template_3points=True,
save_ext='png',
device=device)
face_helper.read_image(img)
# get face landmarks for each face
face_helper.get_face_landmarks_5(
only_center_face=False, eye_dist_threshold=None)
# align and warp each face
face_helper.align_warp_face()
for i, img in enumerate(face_helper.cropped_faces):
# prepare data
data = dict(lq=img.astype(np.float32))
data = test_pipeline(data)
data = scatter(collate([data], samples_per_gpu=1), [device])[0]
with torch.no_grad():
output = model(test_mode=True, **data)['output'].clip_(0, 1)
output = output.squeeze(0).permute(1, 2, 0)[:, :, [2, 1, 0]]
output = output.cpu().numpy() * 255 # (0, 255)
face_helper.add_restored_face(output)
face_helper.get_inverse_affine(None)
restored_img = face_helper.paste_faces_to_input_image(upsample_img=None)
return restored_img
| 3,069 | 33.494382 | 77 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/mmedit/apis/generation_inference.py | # Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
import torch
from mmcv.parallel import collate, scatter
from mmedit.core import tensor2img
from mmedit.datasets.pipelines import Compose
def generation_inference(model, img, img_unpaired=None):
"""Inference image with the model.
Args:
model (nn.Module): The loaded model.
img (str): File path of input image.
img_unpaired (str, optional): File path of the unpaired image.
If not None, perform unpaired image generation. Default: None.
Returns:
np.ndarray: The predicted generation result.
"""
cfg = model.cfg
device = next(model.parameters()).device # model device
# build the data pipeline
test_pipeline = Compose(cfg.test_pipeline)
# prepare data
if img_unpaired is None:
data = dict(pair_path=img)
else:
data = dict(img_a_path=img, img_b_path=img_unpaired)
data = test_pipeline(data)
data = scatter(collate([data], samples_per_gpu=1), [device])[0]
# forward the model
with torch.no_grad():
results = model(test_mode=True, **data)
# process generation shown mode
if img_unpaired is None:
if model.show_input:
output = np.concatenate([
tensor2img(results['real_a'], min_max=(-1, 1)),
tensor2img(results['fake_b'], min_max=(-1, 1)),
tensor2img(results['real_b'], min_max=(-1, 1))
],
axis=1)
else:
output = tensor2img(results['fake_b'], min_max=(-1, 1))
else:
if model.show_input:
output = np.concatenate([
tensor2img(results['real_a'], min_max=(-1, 1)),
tensor2img(results['fake_b'], min_max=(-1, 1)),
tensor2img(results['real_b'], min_max=(-1, 1)),
tensor2img(results['fake_a'], min_max=(-1, 1))
],
axis=1)
else:
if model.test_direction == 'a2b':
output = tensor2img(results['fake_b'], min_max=(-1, 1))
else:
output = tensor2img(results['fake_a'], min_max=(-1, 1))
return output
| 2,229 | 34.967742 | 74 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/mmedit/apis/inpainting_inference.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch
from mmcv.parallel import collate, scatter
from mmedit.datasets.pipelines import Compose
def inpainting_inference(model, masked_img, mask):
"""Inference image with the model.
Args:
model (nn.Module): The loaded model.
masked_img (str): File path of image with mask.
mask (str): Mask file path.
Returns:
Tensor: The predicted inpainting result.
"""
device = next(model.parameters()).device # model device
infer_pipeline = [
dict(type='LoadImageFromFile', key='masked_img'),
dict(type='LoadMask', mask_mode='file', mask_config=dict()),
dict(type='Pad', keys=['masked_img', 'mask'], mode='reflect'),
dict(
type='Normalize',
keys=['masked_img'],
mean=[127.5] * 3,
std=[127.5] * 3,
to_rgb=False),
dict(type='GetMaskedImage', img_name='masked_img'),
dict(
type='Collect',
keys=['masked_img', 'mask'],
meta_keys=['masked_img_path']),
dict(type='ImageToTensor', keys=['masked_img', 'mask'])
]
# build the data pipeline
test_pipeline = Compose(infer_pipeline)
# prepare data
data = dict(masked_img_path=masked_img, mask_path=mask)
data = test_pipeline(data)
data = scatter(collate([data], samples_per_gpu=1), [device])[0]
# forward the model
with torch.no_grad():
result = model(test_mode=True, **data)
return result['fake_img']
| 1,546 | 29.94 | 70 | py |
BasicVSR_PlusPlus | BasicVSR_PlusPlus-master/mmedit/apis/restoration_inference.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch
from mmcv.parallel import collate, scatter
from mmedit.datasets.pipelines import Compose
def restoration_inference(model, img, ref=None):
"""Inference image with the model.
Args:
model (nn.Module): The loaded model.
img (str): File path of input image.
ref (str | None): File path of reference image. Default: None.
Returns:
Tensor: The predicted restoration result.
"""
cfg = model.cfg
device = next(model.parameters()).device # model device
# remove gt from test_pipeline
keys_to_remove = ['gt', 'gt_path']
for key in keys_to_remove:
for pipeline in list(cfg.test_pipeline):
if 'key' in pipeline and key == pipeline['key']:
cfg.test_pipeline.remove(pipeline)
if 'keys' in pipeline and key in pipeline['keys']:
pipeline['keys'].remove(key)
if len(pipeline['keys']) == 0:
cfg.test_pipeline.remove(pipeline)
if 'meta_keys' in pipeline and key in pipeline['meta_keys']:
pipeline['meta_keys'].remove(key)
# build the data pipeline
test_pipeline = Compose(cfg.test_pipeline)
# prepare data
if ref: # Ref-SR
data = dict(lq_path=img, ref_path=ref)
else: # SISR
data = dict(lq_path=img)
data = test_pipeline(data)
data = scatter(collate([data], samples_per_gpu=1), [device])[0]
# forward the model
with torch.no_grad():
result = model(test_mode=True, **data)
return result['output']
| 1,606 | 33.191489 | 72 | py |