code
stringlengths
17
6.64M
def is_rocm_pytorch() -> bool: is_rocm = False if (TORCH_VERSION != 'parrots'): try: from torch.utils.cpp_extension import ROCM_HOME is_rocm = (True if ((torch.version.hip is not None) and (ROCM_HOME is not None)) else False) except ImportError: pass ret...
def _get_cuda_home(): if (TORCH_VERSION == 'parrots'): from parrots.utils.build_extension import CUDA_HOME elif is_rocm_pytorch(): from torch.utils.cpp_extension import ROCM_HOME CUDA_HOME = ROCM_HOME else: from torch.utils.cpp_extension import CUDA_HOME return CUDA_HOM...
def get_build_config(): if (TORCH_VERSION == 'parrots'): from parrots.config import get_build_info return get_build_info() else: return torch.__config__.show()
def _get_conv(): if (TORCH_VERSION == 'parrots'): from parrots.nn.modules.conv import _ConvNd, _ConvTransposeMixin else: from torch.nn.modules.conv import _ConvNd, _ConvTransposeMixin return (_ConvNd, _ConvTransposeMixin)
def _get_dataloader(): if (TORCH_VERSION == 'parrots'): from torch.utils.data import DataLoader, PoolDataLoader else: from torch.utils.data import DataLoader PoolDataLoader = DataLoader return (DataLoader, PoolDataLoader)
def _get_extension(): if (TORCH_VERSION == 'parrots'): from parrots.utils.build_extension import BuildExtension, Extension CppExtension = partial(Extension, cuda=False) CUDAExtension = partial(Extension, cuda=True) else: from torch.utils.cpp_extension import BuildExtension, Cpp...
def _get_pool(): if (TORCH_VERSION == 'parrots'): from parrots.nn.modules.pool import _AdaptiveAvgPoolNd, _AdaptiveMaxPoolNd, _AvgPoolNd, _MaxPoolNd else: from torch.nn.modules.pooling import _AdaptiveAvgPoolNd, _AdaptiveMaxPoolNd, _AvgPoolNd, _MaxPoolNd return (_AdaptiveAvgPoolNd, _Adapti...
def _get_norm(): if (TORCH_VERSION == 'parrots'): from parrots.nn.modules.batchnorm import _BatchNorm, _InstanceNorm SyncBatchNorm_ = torch.nn.SyncBatchNorm2d else: from torch.nn.modules.batchnorm import _BatchNorm from torch.nn.modules.instancenorm import _InstanceNorm ...
class SyncBatchNorm(SyncBatchNorm_): def _check_input_dim(self, input): if (TORCH_VERSION == 'parrots'): if (input.dim() < 2): raise ValueError(f'expected at least 2D input (got {input.dim()}D input)') else: super()._check_input_dim(input)
def is_filepath(x): return (is_str(x) or isinstance(x, Path))
def fopen(filepath, *args, **kwargs): if is_str(filepath): return open(filepath, *args, **kwargs) elif isinstance(filepath, Path): return filepath.open(*args, **kwargs) raise ValueError('`filepath` should be a string or a Path')
def check_file_exist(filename, msg_tmpl='file "{}" does not exist'): if (not osp.isfile(filename)): raise FileNotFoundError(msg_tmpl.format(filename))
def mkdir_or_exist(dir_name, mode=511): if (dir_name == ''): return dir_name = osp.expanduser(dir_name) os.makedirs(dir_name, mode=mode, exist_ok=True)
def symlink(src, dst, overwrite=True, **kwargs): if (os.path.lexists(dst) and overwrite): os.remove(dst) os.symlink(src, dst, **kwargs)
def scandir(dir_path, suffix=None, recursive=False, case_sensitive=True): 'Scan a directory to find the interested files.\n\n Args:\n dir_path (str | :obj:`Path`): Path of the directory.\n suffix (str | tuple(str), optional): File suffix that we are\n interested in. Default: None.\n ...
def find_vcs_root(path, markers=('.git',)): 'Finds the root directory (including itself) of specified markers.\n\n Args:\n path (str): Path of directory or file.\n markers (list[str], optional): List of file or directory names.\n\n Returns:\n The directory contained one of the markers o...
class ProgressBar(): 'A progress bar which can print the progress.' def __init__(self, task_num=0, bar_width=50, start=True, file=sys.stdout): self.task_num = task_num self.bar_width = bar_width self.completed = 0 self.file = file if start: self.start() ...
def track_progress(func, tasks, bar_width=50, file=sys.stdout, **kwargs): 'Track the progress of tasks execution with a progress bar.\n\n Tasks are done with a simple for-loop.\n\n Args:\n func (callable): The function to be applied to each task.\n tasks (list or tuple[Iterable, int]): A list ...
def init_pool(process_num, initializer=None, initargs=None): if (initializer is None): return Pool(process_num) elif (initargs is None): return Pool(process_num, initializer) else: if (not isinstance(initargs, tuple)): raise TypeError('"initargs" must be a tuple') ...
def track_parallel_progress(func, tasks, nproc, initializer=None, initargs=None, bar_width=50, chunksize=1, skip_first=False, keep_order=True, file=sys.stdout): 'Track the progress of parallel task execution with a progress bar.\n\n The built-in :mod:`multiprocessing` module is used for process pools and\n ...
def track_iter_progress(tasks, bar_width=50, file=sys.stdout): 'Track the progress of tasks iteration or enumeration with a progress\n bar.\n\n Tasks are yielded with a simple for-loop.\n\n Args:\n tasks (list or tuple[Iterable, int]): A list of tasks or\n (tasks, total num).\n b...
def build_from_cfg(cfg, registry, default_args=None): 'Build a module from config dict.\n\n Args:\n cfg (dict): Config dict. It should at least contain the key "type".\n registry (:obj:`Registry`): The registry to search the type from.\n default_args (dict, optional): Default initializatio...
class Registry(): "A registry to map strings to classes.\n\n Registered object could be built from registry.\n\n Example:\n >>> MODELS = Registry('models')\n >>> @MODELS.register_module()\n >>> class ResNet:\n >>> pass\n >>> resnet = MODELS.build(dict(type='ResNet'))\n...
def worker_init_fn(worker_id: int, num_workers: int, rank: int, seed: int): 'Function to initialize each worker.\n\n The seed of each worker equals to\n ``num_worker * rank + worker_id + user_seed``.\n\n Args:\n worker_id (int): Id for each worker.\n num_workers (int): Number of workers.\n ...
def check_python_script(cmd): 'Run the python cmd script with `__main__`. The difference between\n `os.system` is that, this function exectues code in the current process, so\n that it can be tracked by coverage tools. Currently it supports two forms:\n\n - ./tests/data/scripts/hello.py zz\n - python ...
def _any(judge_result): 'Since built-in ``any`` works only when the element of iterable is not\n iterable, implement the function.' if (not isinstance(judge_result, Iterable)): return judge_result try: for element in judge_result: if _any(element): return Tru...
def assert_dict_contains_subset(dict_obj: Dict[(Any, Any)], expected_subset: Dict[(Any, Any)]) -> bool: 'Check if the dict_obj contains the expected_subset.\n\n Args:\n dict_obj (Dict[Any, Any]): Dict object to be checked.\n expected_subset (Dict[Any, Any]): Subset expected to be contained in\n ...
def assert_attrs_equal(obj: Any, expected_attrs: Dict[(str, Any)]) -> bool: 'Check if attribute of class object is correct.\n\n Args:\n obj (object): Class object to be checked.\n expected_attrs (Dict[str, Any]): Dict of the expected attrs.\n\n Returns:\n bool: Whether the attribute of ...
def assert_dict_has_keys(obj: Dict[(str, Any)], expected_keys: List[str]) -> bool: 'Check if the obj has all the expected_keys.\n\n Args:\n obj (Dict[str, Any]): Object to be checked.\n expected_keys (List[str]): Keys expected to contained in the keys of\n the obj.\n\n Returns:\n ...
def assert_keys_equal(result_keys: List[str], target_keys: List[str]) -> bool: 'Check if target_keys is equal to result_keys.\n\n Args:\n result_keys (List[str]): Result keys to be checked.\n target_keys (List[str]): Target keys to be checked.\n\n Returns:\n bool: Whether target_keys is...
def assert_is_norm_layer(module) -> bool: 'Check if the module is a norm layer.\n\n Args:\n module (nn.Module): The module to be checked.\n\n Returns:\n bool: Whether the module is a norm layer.\n ' from torch.nn import GroupNorm, LayerNorm from .parrots_wrapper import _BatchNorm, _...
def assert_params_all_zeros(module) -> bool: 'Check if the parameters of the module is all zeros.\n\n Args:\n module (nn.Module): The module to be checked.\n\n Returns:\n bool: Whether the parameters of the module is all zeros.\n ' weight_data = module.weight.data is_weight_zero = w...
class TimerError(Exception): def __init__(self, message): self.message = message super(TimerError, self).__init__(message)
class Timer(): "A flexible Timer class.\n\n Examples:\n >>> import time\n >>> import mmcv\n >>> with mmcv.Timer():\n >>> # simulate a code block that will run for 1s\n >>> time.sleep(1)\n 1.000\n >>> with mmcv.Timer(print_tmpl='it takes {:.1f} seconds'):...
def check_time(timer_id): "Add check points in a single line.\n\n This method is suitable for running a task on a list of items. A timer will\n be registered when the method is called for the first time.\n\n Examples:\n >>> import time\n >>> import mmcv\n >>> for i in range(1, 6):\n ...
def is_jit_tracing() -> bool: if ((torch.__version__ != 'parrots') and (digit_version(torch.__version__) >= digit_version('1.6.0'))): on_trace = torch.jit.is_tracing() if isinstance(on_trace, bool): return on_trace else: return torch._C._is_tracing() else: ...
def digit_version(version_str: str, length: int=4): 'Convert a version string into a tuple of integers.\n\n This method is usually used for comparing two versions. For pre-release\n versions: alpha < beta < rc.\n\n Args:\n version_str (str): The version string.\n length (int): The maximum n...
def _minimal_ext_cmd(cmd): env = {} for k in ['SYSTEMROOT', 'PATH', 'HOME']: v = os.environ.get(k) if (v is not None): env[k] = v env['LANGUAGE'] = 'C' env['LANG'] = 'C' env['LC_ALL'] = 'C' out = subprocess.Popen(cmd, stdout=subprocess.PIPE, env=env).communicate()[0...
def get_git_hash(fallback='unknown', digits=None): "Get the git hash of the current repo.\n\n Args:\n fallback (str, optional): The fallback string when git hash is\n unavailable. Defaults to 'unknown'.\n digits (int, optional): kept digits of the hash. Defaults to None,\n m...
def parse_version_info(version_str: str, length: int=4) -> tuple: 'Parse a version string into a tuple.\n\n Args:\n version_str (str): The version string.\n length (int): The maximum number of version levels. Default: 4.\n\n Returns:\n tuple[int | str]: The version info, e.g., "1.3.0" i...
class Cache(): def __init__(self, capacity): self._cache = OrderedDict() self._capacity = int(capacity) if (capacity <= 0): raise ValueError('capacity must be a positive integer') @property def capacity(self): return self._capacity @property def size(...
class VideoReader(): "Video class with similar usage to a list object.\n\n This video warpper class provides convenient apis to access frames.\n There exists an issue of OpenCV's VideoCapture class that jumping to a\n certain frame may be inaccurate. It is fixed in this class by checking\n the positio...
def frames2video(frame_dir, video_file, fps=30, fourcc='XVID', filename_tmpl='{:06d}.jpg', start=0, end=0, show_progress=True): 'Read the frame images from a directory and join them as a video.\n\n Args:\n frame_dir (str): The directory containing video frames.\n video_file (str): Output filename...
@requires_executable('ffmpeg') def convert_video(in_file, out_file, print_cmd=False, pre_options='', **kwargs): 'Convert a video with ffmpeg.\n\n This provides a general api to ffmpeg, the executed command is::\n\n `ffmpeg -y <pre_options> -i <in_file> <options> <out_file>`\n\n Options(kwargs) are ma...
@requires_executable('ffmpeg') def resize_video(in_file, out_file, size=None, ratio=None, keep_ar=False, log_level='info', print_cmd=False): 'Resize a video.\n\n Args:\n in_file (str): Input video filename.\n out_file (str): Output video filename.\n size (tuple): Expected size (w, h), eg, ...
@requires_executable('ffmpeg') def cut_video(in_file, out_file, start=None, end=None, vcodec=None, acodec=None, log_level='info', print_cmd=False): 'Cut a clip from a video.\n\n Args:\n in_file (str): Input video filename.\n out_file (str): Output video filename.\n start (None or float): S...
@requires_executable('ffmpeg') def concat_video(video_list, out_file, vcodec=None, acodec=None, log_level='info', print_cmd=False): 'Concatenate multiple videos into a single one.\n\n Args:\n video_list (list): A list of video filenames\n out_file (str): Output video filename\n vcodec (Non...
class Color(Enum): 'An enum that defines common colors.\n\n Contains red, green, blue, cyan, yellow, magenta, white and black.\n ' red = (0, 0, 255) green = (0, 255, 0) blue = (255, 0, 0) cyan = (255, 255, 0) yellow = (0, 255, 255) magenta = (255, 0, 255) white = (255, 255, 255) ...
def color_val(color): 'Convert various input to color tuples.\n\n Args:\n color (:obj:`Color`/str/tuple/int/ndarray): Color inputs\n\n Returns:\n tuple[int]: A tuple of 3 integers indicating BGR channels.\n ' if is_str(color): return Color[color].value elif isinstance(color,...
def choose_requirement(primary, secondary): 'If some version of primary requirement installed, return primary, else\n return secondary.' try: name = re.split('[!<>=]', primary)[0] get_distribution(name) except DistributionNotFound: return secondary return str(primary)
def get_version(): version_file = 'mmcv/version.py' with open(version_file, 'r', encoding='utf-8') as f: exec(compile(f.read(), version_file, 'exec')) return locals()['__version__']
def parse_requirements(fname='requirements/runtime.txt', with_version=True): 'Parse the package dependencies listed in a requirements file but strips\n specific versioning information.\n\n Args:\n fname (str): path to requirements file\n with_version (bool, default=False): if True include vers...
def get_extensions(): extensions = [] if (os.getenv('MMCV_WITH_TRT', '0') != '0'): (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) m...
def test_quantize(): arr = np.random.randn(10, 10) levels = 20 qarr = mmcv.quantize(arr, (- 1), 1, levels) assert (qarr.shape == arr.shape) assert (qarr.dtype == np.dtype('int64')) for i in range(arr.shape[0]): for j in range(arr.shape[1]): ref = min((levels - 1), int(np.fl...
def test_dequantize(): levels = 20 qarr = np.random.randint(levels, size=(10, 10)) arr = mmcv.dequantize(qarr, (- 1), 1, levels) assert (arr.shape == qarr.shape) assert (arr.dtype == np.dtype('float64')) for i in range(qarr.shape[0]): for j in range(qarr.shape[1]): assert (...
def test_joint(): arr = np.random.randn(100, 100) levels = 1000 qarr = mmcv.quantize(arr, (- 1), 1, levels) recover = mmcv.dequantize(qarr, (- 1), 1, levels) assert (np.abs((recover[(arr < (- 1))] + 0.999)).max() < 1e-06) assert (np.abs((recover[(arr > 1)] - 0.999)).max() < 1e-06) assert (...
def test_build_conv_layer(): with pytest.raises(TypeError): cfg = 'Conv2d' build_conv_layer(cfg) with pytest.raises(KeyError): cfg = dict(kernel_size=3) build_conv_layer(cfg) with pytest.raises(KeyError): cfg = dict(type='FancyConv') build_conv_layer(cfg) ...
def test_infer_norm_abbr(): with pytest.raises(TypeError): infer_norm_abbr(0) class MyNorm(): _abbr_ = 'mn' assert (infer_norm_abbr(MyNorm) == 'mn') class FancyBatchNorm(): pass assert (infer_norm_abbr(FancyBatchNorm) == 'bn') class FancyInstanceNorm(): pass ...
def test_build_norm_layer(): with pytest.raises(TypeError): cfg = 'BN' build_norm_layer(cfg, 3) with pytest.raises(KeyError): cfg = dict() build_norm_layer(cfg, 3) with pytest.raises(KeyError): cfg = dict(type='FancyNorm') build_norm_layer(cfg, 3) with p...
def test_build_activation_layer(): with pytest.raises(TypeError): cfg = 'ReLU' build_activation_layer(cfg) with pytest.raises(KeyError): cfg = dict() build_activation_layer(cfg) with pytest.raises(KeyError): cfg = dict(type='FancyReLU') build_activation_laye...
def test_build_padding_layer(): with pytest.raises(TypeError): cfg = 'reflect' build_padding_layer(cfg) with pytest.raises(KeyError): cfg = dict() build_padding_layer(cfg) with pytest.raises(KeyError): cfg = dict(type='FancyPad') build_padding_layer(cfg) ...
def test_upsample_layer(): with pytest.raises(TypeError): cfg = 'bilinear' build_upsample_layer(cfg) with pytest.raises(KeyError): cfg = dict() build_upsample_layer(cfg) with pytest.raises(KeyError): cfg = dict(type='FancyUpsample') build_upsample_layer(cfg)...
def test_pixel_shuffle_pack(): x_in = torch.rand(2, 3, 10, 10) pixel_shuffle = PixelShufflePack(3, 3, scale_factor=2, upsample_kernel=3) assert (pixel_shuffle.upsample_conv.kernel_size == (3, 3)) x_out = pixel_shuffle(x_in) assert (x_out.shape == (2, 3, 20, 20))
def test_is_norm(): norm_set1 = [nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d, nn.InstanceNorm1d, nn.InstanceNorm2d, nn.InstanceNorm3d, nn.LayerNorm] norm_set2 = [nn.GroupNorm] for norm_type in norm_set1: layer = norm_type(3) assert is_norm(layer) assert (not is_norm(layer, exclu...
def test_infer_plugin_abbr(): with pytest.raises(TypeError): infer_plugin_abbr(0) class MyPlugin(): _abbr_ = 'mp' assert (infer_plugin_abbr(MyPlugin) == 'mp') class FancyPlugin(): pass assert (infer_plugin_abbr(FancyPlugin) == 'fancy_plugin')
def test_build_plugin_layer(): with pytest.raises(TypeError): cfg = 'Plugin' build_plugin_layer(cfg) with pytest.raises(KeyError): cfg = dict() build_plugin_layer(cfg) with pytest.raises(KeyError): cfg = dict(type='FancyPlugin') build_plugin_layer(cfg) w...
def test_context_block(): with pytest.raises(AssertionError): ContextBlock(16, (1.0 / 4), pooling_type='unsupport_type') with pytest.raises(AssertionError): ContextBlock(16, (1.0 / 4), fusion_types='unsupport_type') with pytest.raises(AssertionError): ContextBlock(16, (1.0 / 4), fu...
def test_conv2d_samepadding(): inputs = torch.rand((1, 3, 28, 28)) conv = Conv2dAdaptivePadding(3, 3, kernel_size=3, stride=1) output = conv(inputs) assert (output.shape == inputs.shape) inputs = torch.rand((1, 3, 13, 13)) conv = Conv2dAdaptivePadding(3, 3, kernel_size=3, stride=1) output ...
@CONV_LAYERS.register_module() class ExampleConv(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, norm_cfg=None): super(ExampleConv, self).__init__() self.in_channels = in_channels self.out_channels = out_channels...
def test_conv_module(): with pytest.raises(AssertionError): conv_cfg = 'conv' ConvModule(3, 8, 2, conv_cfg=conv_cfg) with pytest.raises(AssertionError): norm_cfg = 'norm' ConvModule(3, 8, 2, norm_cfg=norm_cfg) with pytest.raises(KeyError): act_cfg = dict(type='softm...
def test_bias(): conv = ConvModule(3, 8, 2) assert (conv.conv.bias is not None) conv = ConvModule(3, 8, 2, norm_cfg=dict(type='BN')) assert (conv.conv.bias is None) conv = ConvModule(3, 8, 2, bias=False) assert (conv.conv.bias is None) with pytest.warns(UserWarning) as record: Conv...
def conv_forward(self, x): return (x + '_conv')
def bn_forward(self, x): return (x + '_bn')
def relu_forward(self, x): return (x + '_relu')
@patch('torch.nn.ReLU.forward', relu_forward) @patch('torch.nn.BatchNorm2d.forward', bn_forward) @patch('torch.nn.Conv2d.forward', conv_forward) def test_order(): with pytest.raises(AssertionError): order = ['conv', 'norm', 'act'] ConvModule(3, 8, 2, order=order) with pytest.raises(AssertionEr...
def test_depthwise_separable_conv(): with pytest.raises(AssertionError): DepthwiseSeparableConvModule(4, 8, 2, groups=2) conv = DepthwiseSeparableConvModule(3, 8, 2) assert (conv.depthwise_conv.conv.groups == 3) assert (conv.pointwise_conv.conv.kernel_size == (1, 1)) assert (not conv.depth...
class ExampleModel(nn.Module): def __init__(self): super().__init__() self.conv2d = nn.Conv2d(3, 8, 3) def forward(self, imgs): x = torch.randn((1, *imgs)) return self.conv2d(x)
def input_constructor(x): return dict(imgs=x)
def test_flops_counter(): with pytest.raises(AssertionError): model = nn.Conv2d(3, 8, 3) input_res = [1, 3, 16, 16] get_model_complexity_info(model, input_res) with pytest.raises(AssertionError): model = nn.Conv2d(3, 8, 3) input_res = tuple() get_model_complexit...
def test_flops_to_string(): flops = (6.54321 * (10.0 ** 9)) assert (flops_to_string(flops) == '6.54 GFLOPs') assert (flops_to_string(flops, 'MFLOPs') == '6543.21 MFLOPs') assert (flops_to_string(flops, 'KFLOPs') == '6543210.0 KFLOPs') assert (flops_to_string(flops, 'FLOPs') == '6543210000.0 FLOPs'...
def test_params_to_string(): num_params = (3.21 * (10.0 ** 7)) assert (params_to_string(num_params) == '32.1 M') num_params = (4.56 * (10.0 ** 5)) assert (params_to_string(num_params) == '456.0 k') num_params = (7.89 * (10.0 ** 2)) assert (params_to_string(num_params) == '789.0') num_param...
def test_fuse_conv_bn(): inputs = torch.rand((1, 3, 5, 5)) modules = nn.ModuleList() modules.append(nn.BatchNorm2d(3)) modules.append(ConvModule(3, 5, 3, norm_cfg=dict(type='BN'))) modules.append(ConvModule(5, 5, 3, norm_cfg=dict(type='BN'))) modules = nn.Sequential(*modules) fused_modules...
def test_context_block(): imgs = torch.randn(2, 16, 20, 20) gen_attention_block = GeneralizedAttention(16, attention_type='1000') assert (gen_attention_block.query_conv.in_channels == 16) assert (gen_attention_block.key_conv.in_channels == 16) assert (gen_attention_block.key_conv.in_channels == 16...
def test_hsigmoid(): with pytest.raises(AssertionError): HSigmoid(divisor=0) act = HSigmoid() input_shape = torch.Size([1, 3, 64, 64]) input = torch.randn(input_shape) output = act(input) expected_output = torch.min(torch.max(((input + 3) / 6), torch.zeros(input_shape)), torch.ones(inp...
def test_hswish(): act = HSwish(inplace=True) assert act.act.inplace act = HSwish() assert (not act.act.inplace) input = torch.randn(1, 3, 64, 64) expected_output = ((input * relu6((input + 3))) / 6) output = act(input) assert (output.shape == expected_output.shape) assert torch.eq...
def test_build_model_from_cfg(): BACKBONES = mmcv.Registry('backbone', build_func=build_model_from_cfg) @BACKBONES.register_module() class ResNet(nn.Module): def __init__(self, depth, stages=4): super().__init__() self.depth = depth self.stages = stages ...
def test_nonlocal(): with pytest.raises(ValueError): _NonLocalNd(3, mode='unsupport_mode') _NonLocalNd(3) _NonLocalNd(3, norm_cfg=dict(type='BN')) _NonLocalNd(3, zeros_init=False) _NonLocalNd(3, norm_cfg=dict(type='BN'), zeros_init=False)
def test_nonlocal3d(): imgs = torch.randn(2, 3, 10, 20, 20) nonlocal_3d = NonLocal3d(3) if (torch.__version__ == 'parrots'): if torch.cuda.is_available(): imgs = imgs.cuda() nonlocal_3d.cuda() out = nonlocal_3d(imgs) assert (out.shape == imgs.shape) nonlocal_3d ...
def test_nonlocal2d(): imgs = torch.randn(2, 3, 20, 20) nonlocal_2d = NonLocal2d(3) if (torch.__version__ == 'parrots'): if torch.cuda.is_available(): imgs = imgs.cuda() nonlocal_2d.cuda() out = nonlocal_2d(imgs) assert (out.shape == imgs.shape) imgs = torch.ran...
def test_nonlocal1d(): imgs = torch.randn(2, 3, 20) nonlocal_1d = NonLocal1d(3) if (torch.__version__ == 'parrots'): if torch.cuda.is_available(): imgs = imgs.cuda() nonlocal_1d.cuda() out = nonlocal_1d(imgs) assert (out.shape == imgs.shape) imgs = torch.randn(2...
def test_revert_syncbn(): conv = ConvModule(3, 8, 2, norm_cfg=dict(type='SyncBN')) x = torch.randn(1, 3, 10, 10) with pytest.raises(ValueError): y = conv(x) conv = revert_sync_batchnorm(conv) y = conv(x) assert (y.shape == (1, 8, 9, 9))
def test_revert_mmsyncbn(): if (('SLURM_NTASKS' not in os.environ) or (int(os.environ['SLURM_NTASKS']) < 2)): print('Must run on slurm with more than 1 process!\nsrun -p test --gres=gpu:2 -n2') return rank = int(os.environ['SLURM_PROCID']) world_size = int(os.environ['SLURM_NTASKS']) l...
def test_scale(): scale = Scale() assert (scale.scale.data == 1.0) assert (scale.scale.dtype == torch.float) x = torch.rand(1, 3, 64, 64) output = scale(x) assert (output.shape == (1, 3, 64, 64)) scale = Scale(10.0) assert (scale.scale.data == 10.0) assert (scale.scale.dtype == tor...
def test_swish(): act = Swish() input = torch.randn(1, 3, 64, 64) expected_output = (input * F.sigmoid(input)) output = act(input) assert (output.shape == expected_output.shape) assert torch.equal(output, expected_output)
def test_adaptive_padding(): for padding in ('same', 'corner'): kernel_size = 16 stride = 16 dilation = 1 input = torch.rand(1, 1, 15, 17) adap_pad = AdaptivePadding(kernel_size=kernel_size, stride=stride, dilation=dilation, padding=padding) out = adap_pad(input) ...
def test_patch_embed(): B = 2 H = 3 W = 4 C = 3 embed_dims = 10 kernel_size = 3 stride = 1 dummy_input = torch.rand(B, C, H, W) patch_merge_1 = PatchEmbed(in_channels=C, embed_dims=embed_dims, kernel_size=kernel_size, stride=stride, padding=0, dilation=1, norm_cfg=None) (x1, sh...
def test_patch_merging(): in_c = 3 out_c = 4 kernel_size = 3 stride = 3 padding = 1 dilation = 1 bias = False patch_merge = PatchMerging(in_channels=in_c, out_channels=out_c, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation, bias=bias) (B, L, C) = (1, 100,...
def test_multiheadattention(): MultiheadAttention(embed_dims=5, num_heads=5, attn_drop=0, proj_drop=0, dropout_layer=dict(type='Dropout', drop_prob=0.0), batch_first=True) batch_dim = 2 embed_dim = 5 num_query = 100 attn_batch_first = MultiheadAttention(embed_dims=5, num_heads=5, attn_drop=0, proj...
def test_ffn(): with pytest.raises(AssertionError): FFN(num_fcs=1) FFN(dropout=0, add_residual=True) ffn = FFN(dropout=0, add_identity=True) input_tensor = torch.rand(2, 20, 256) input_tensor_nbc = input_tensor.transpose(0, 1) assert torch.allclose(ffn(input_tensor).sum(), ffn(input_te...
@pytest.mark.skipif((not torch.cuda.is_available()), reason='Cuda not available') def test_basetransformerlayer_cuda(): operation_order = ('self_attn', 'ffn') baselayer = BaseTransformerLayer(operation_order=operation_order, batch_first=True, attn_cfgs=dict(type='MultiheadAttention', embed_dims=256, num_heads...