code
stringlengths
17
6.64M
def _test_roialign_allclose(device, dtype): if ((not torch.cuda.is_available()) and (device == 'cuda')): pytest.skip('test requires GPU') try: from mmcv.ops import roi_align except ModuleNotFoundError: pytest.skip('test requires compilation') pool_h = 2 pool_w = 2 spati...
@pytest.mark.parametrize('device', ['cuda', 'cpu']) @pytest.mark.parametrize('dtype', [torch.float, torch.double, torch.half]) def test_roialign(device, dtype): if (dtype is torch.double): _test_roialign_gradcheck(device=device, dtype=dtype) _test_roialign_allclose(device=device, dtype=dtype)
def _test_roialign_rotated_gradcheck(device, dtype): if ((not torch.cuda.is_available()) and (device == 'cuda')): pytest.skip('unittest does not support GPU yet.') try: from mmcv.ops import RoIAlignRotated except ModuleNotFoundError: pytest.skip('RoIAlignRotated op is not successfu...
def _test_roialign_rotated_allclose(device, dtype): if ((not torch.cuda.is_available()) and (device == 'cuda')): pytest.skip('unittest does not support GPU yet.') try: from mmcv.ops import RoIAlignRotated, roi_align_rotated except ModuleNotFoundError: pytest.skip('test requires com...
@pytest.mark.parametrize('device', ['cuda', 'cpu']) @pytest.mark.parametrize('dtype', [torch.float, torch.double, torch.half]) def test_roialign_rotated(device, dtype): if (dtype is torch.double): _test_roialign_rotated_gradcheck(device=device, dtype=dtype) _test_roialign_rotated_allclose(device=devic...
class TestRoiPool(object): def test_roipool_gradcheck(self): if (not torch.cuda.is_available()): return from mmcv.ops import RoIPool pool_h = 2 pool_w = 2 spatial_scale = 1.0 for case in inputs: np_input = np.array(case[0]) np_ro...
@pytest.mark.skipif((not torch.cuda.is_available()), reason='requires CUDA support') def test_RoIAwarePool3d(): roiaware_pool3d_max = RoIAwarePool3d(out_size=4, max_pts_per_voxel=128, mode='max') roiaware_pool3d_avg = RoIAwarePool3d(out_size=4, max_pts_per_voxel=128, mode='avg') rois = torch.tensor([[1.0,...
@pytest.mark.skipif((not torch.cuda.is_available()), reason='requires CUDA support') def test_points_in_boxes_part(): boxes = torch.tensor([[[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 0.3]], [[(- 10.0), 23.0, 16.0, 10, 20, 20, 0.5]]], dtype=torch.float32).cuda() pts = torch.tensor([[[1, 2, 3.3], [1.2, 2.5, 3.0], [0.8, 2....
def test_points_in_boxes_cpu(): boxes = torch.tensor([[[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 0.3], [(- 10.0), 23.0, 16.0, 10, 20, 20, 0.5]]], dtype=torch.float32) pts = torch.tensor([[[1, 2, 3.3], [1.2, 2.5, 3.0], [0.8, 2.1, 3.5], [1.6, 2.6, 3.6], [0.8, 1.2, 3.9], [(- 9.2), 21.0, 18.2], [3.8, 7.9, 6.3], [4.7, 3.5, (...
@pytest.mark.skipif((not torch.cuda.is_available()), reason='requires CUDA support') def test_points_in_boxes_all(): boxes = torch.tensor([[[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 0.3], [(- 10.0), 23.0, 16.0, 10, 20, 20, 0.5]]], dtype=torch.float32).cuda() pts = torch.tensor([[[1, 2, 3.3], [1.2, 2.5, 3.0], [0.8, 2.1, ...
@pytest.mark.skipif((not torch.cuda.is_available()), reason='requires CUDA support') def test_gather_points(): feats = torch.tensor([[1, 2, 3.3], [1.2, 2.5, 3.0], [0.8, 2.1, 3.5], [1.6, 2.6, 3.6], [0.8, 1.2, 3.9], [(- 9.2), 21.0, 18.2], [3.8, 7.9, 6.3], [4.7, 3.5, (- 12.2)], [3.8, 7.6, (- 2)], [(- 10.6), (- 12.9)...
@pytest.mark.skipif((not torch.cuda.is_available()), reason='requires CUDA support') def test_rotated_feature_align(): feature = torch.tensor([[[[1.2924, (- 0.2172), (- 0.5222), 0.1172], [0.9144, 1.2248, 1.3115, (- 0.969)], [(- 0.8949), (- 1.1797), (- 0.9093), (- 0.3961)], [(- 0.4586), 0.5062, (- 0.7947), (- 0.73...
def test_sacconv(): x = torch.rand(1, 3, 256, 256) saconv = SAConv2d(3, 5, kernel_size=3, padding=1) sac_out = saconv(x) refer_conv = nn.Conv2d(3, 5, kernel_size=3, padding=1) refer_out = refer_conv(x) assert (sac_out.shape == refer_out.shape) dalited_saconv = SAConv2d(3, 5, kernel_size=3,...
def make_sparse_convmodule(in_channels, out_channels, kernel_size, indice_key, stride=1, padding=0, conv_type='SubMConv3d', norm_cfg=None, order=('conv', 'norm', 'act')): 'Make sparse convolution module.\n\n Args:\n in_channels (int): the number of input channels\n out_channels (int): the number ...
@pytest.mark.skipif((not torch.cuda.is_available()), reason='requires CUDA support') def test_make_sparse_convmodule(): voxel_features = torch.tensor([[6.56126, 0.9648336, (- 1.7339306), 0.315], [6.8162713, (- 2.480431), (- 1.3616394), 0.36], [11.643568, (- 4.744306), (- 1.3580885), 0.16], [23.482342, 6.5036807, ...
class TestSyncBN(object): def dist_init(self): rank = int(os.environ['SLURM_PROCID']) world_size = int(os.environ['SLURM_NTASKS']) local_rank = int(os.environ['SLURM_LOCALID']) node_list = str(os.environ['SLURM_NODELIST']) node_parts = re.findall('[0-9]+', node_list) ...
def remove_tmp_file(func): @wraps(func) def wrapper(*args, **kwargs): onnx_file = 'tmp.onnx' kwargs['onnx_file'] = onnx_file try: result = func(*args, **kwargs) finally: if os.path.exists(onnx_file): os.remove(onnx_file) return r...
@remove_tmp_file def export_nms_module_to_onnx(module, onnx_file): torch_model = module() torch_model.eval() input = (torch.rand([100, 4], dtype=torch.float32), torch.rand([100], dtype=torch.float32)) torch.onnx.export(torch_model, input, onnx_file, opset_version=11, input_names=['boxes', 'scores'], o...
def test_can_handle_nms_with_constant_maxnum(): class ModuleNMS(torch.nn.Module): def forward(self, boxes, scores): return nms(boxes, scores, iou_threshold=0.4, max_num=10) onnx_model = export_nms_module_to_onnx(ModuleNMS) preprocess_onnx_model = preprocess_onnx(onnx_model) for n...
def test_can_handle_nms_with_undefined_maxnum(): class ModuleNMS(torch.nn.Module): def forward(self, boxes, scores): return nms(boxes, scores, iou_threshold=0.4) onnx_model = export_nms_module_to_onnx(ModuleNMS) preprocess_onnx_model = preprocess_onnx(onnx_model) for node in prep...
@pytest.mark.skipif((not torch.cuda.is_available()), reason='requires CUDA support') def test_three_interpolate(): features = torch.tensor([[[2.435, 4.7516, 4.4995, 2.435, 2.435, 2.435], [3.1236, 2.6278, 3.0447, 3.1236, 3.1236, 3.1236], [2.6732, 2.8677, 2.6436, 2.6732, 2.6732, 2.6732], [0.0124, 7.015, 7.0199, 0.0...
@pytest.mark.skipif((not torch.cuda.is_available()), reason='requires CUDA support') def test_three_nn(): known = torch.tensor([[[(- 1.8373), 3.5605, (- 0.7867)], [0.7615, 2.942, 0.2314], [(- 0.6503), 3.6637, (- 1.0622)], [(- 1.8373), 3.5605, (- 0.7867)], [(- 1.8373), 3.5605, (- 0.7867)]], [[(- 1.3399), 1.9991, (...
def _test_tinshift_gradcheck(dtype): try: from mmcv.ops import tin_shift except ModuleNotFoundError: pytest.skip('TINShift op is not successfully compiled') if (dtype == torch.half): pytest.skip('"add_cpu/sub_cpu" not implemented for Half') for shift in shifts: np_input...
def _test_tinshift_allclose(dtype): try: from mmcv.ops import tin_shift except ModuleNotFoundError: pytest.skip('TINShift op is not successfully compiled') for (shift, output, grad) in zip(shifts, outputs, grads): np_input = np.array(inputs) np_shift = np.array(shift) ...
def _test_tinshift_assert(dtype): try: from mmcv.ops import tin_shift except ModuleNotFoundError: pytest.skip('TINShift op is not successfully compiled') inputs = [torch.rand(2, 3, 4, 2), torch.rand(2, 3, 4, 2)] shifts = [torch.rand(2, 3), torch.rand(2, 5)] for (x, shift) in zip(in...
@pytest.mark.skipif((not torch.cuda.is_available()), reason='requires CUDA support') @pytest.mark.parametrize('dtype', [torch.float, torch.double, torch.half]) def test_tinshift(dtype): _test_tinshift_allclose(dtype=dtype) _test_tinshift_gradcheck(dtype=dtype) _test_tinshift_assert(dtype=dtype)
def mock(*args, **kwargs): pass
@patch('torch.distributed._broadcast_coalesced', mock) @patch('torch.distributed.broadcast', mock) @patch('torch.nn.parallel.DistributedDataParallel._ddp_init_helper', mock) def test_is_module_wrapper(): class Model(nn.Module): def __init__(self): super().__init__() self.conv = n...
def test_get_input_device(): input = torch.zeros([1, 3, 3, 3]) assert (get_input_device(input) == (- 1)) inputs = [torch.zeros([1, 3, 3, 3]), torch.zeros([1, 4, 4, 4])] assert (get_input_device(inputs) == (- 1)) if torch.cuda.is_available(): input = torch.zeros([1, 3, 3, 3]).cuda() ...
def test_scatter(): input = torch.zeros([1, 3, 3, 3]) output = scatter(input=input, devices=[(- 1)]) assert torch.allclose(input, output) inputs = [torch.zeros([1, 3, 3, 3]), torch.zeros([1, 4, 4, 4])] outputs = scatter(input=inputs, devices=[(- 1)]) for (input, output) in zip(inputs, outputs)...
def test_Scatter(): target_gpus = [(- 1)] input = torch.zeros([1, 3, 3, 3]) outputs = Scatter.forward(target_gpus, input) assert isinstance(outputs, tuple) assert torch.allclose(input, outputs[0]) target_gpus = [(- 1)] inputs = [torch.zeros([1, 3, 3, 3]), torch.zeros([1, 4, 4, 4])] out...
@COMPONENTS.register_module() class FooConv1d(BaseModule): def __init__(self, init_cfg=None): super().__init__(init_cfg) self.conv1d = nn.Conv1d(4, 1, 4) def forward(self, x): return self.conv1d(x)
@COMPONENTS.register_module() class FooConv2d(BaseModule): def __init__(self, init_cfg=None): super().__init__(init_cfg) self.conv2d = nn.Conv2d(3, 1, 3) def forward(self, x): return self.conv2d(x)
@COMPONENTS.register_module() class FooLinear(BaseModule): def __init__(self, init_cfg=None): super().__init__(init_cfg) self.linear = nn.Linear(3, 4) def forward(self, x): return self.linear(x)
@COMPONENTS.register_module() class FooLinearConv1d(BaseModule): def __init__(self, linear=None, conv1d=None, init_cfg=None): super().__init__(init_cfg) if (linear is not None): self.linear = build_from_cfg(linear, COMPONENTS) if (conv1d is not None): self.conv1d =...
@FOOMODELS.register_module() class FooModel(BaseModule): def __init__(self, component1=None, component2=None, component3=None, component4=None, init_cfg=None) -> None: super().__init__(init_cfg) if (component1 is not None): self.component1 = build_from_cfg(component1, COMPONENTS) ...
def test_initilization_info_logger(): import os import torch.nn as nn from mmcv.utils.logging import get_logger class OverloadInitConv(nn.Conv2d, BaseModule): def init_weights(self): for p in self.parameters(): with torch.no_grad(): p.fill_(1) ...
def test_update_init_info(): class DummyModel(BaseModule): def __init__(self, init_cfg=None): super().__init__(init_cfg) self.conv1 = nn.Conv2d(1, 1, 1, 1) self.conv3 = nn.Conv2d(1, 1, 1, 1) self.fc1 = nn.Linear(1, 1) model = DummyModel() from coll...
def test_model_weight_init(): '\n Config\n model (FooModel, Linear: weight=1, bias=2, Conv1d: weight=3, bias=4,\n Conv2d: weight=5, bias=6)\n ├──component1 (FooConv1d)\n ├──component2 (FooConv2d)\n ├──component3 (FooLinear)\n ├──component4 (FooLinearConv1d)\n ├──linear...
def test_nest_components_weight_init(): '\n Config\n model (FooModel, Linear: weight=1, bias=2, Conv1d: weight=3, bias=4,\n Conv2d: weight=5, bias=6)\n ├──component1 (FooConv1d, Conv1d: weight=7, bias=8)\n ├──component2 (FooConv2d, Conv2d: weight=9, bias=10)\n ├──component3 (Foo...
def test_without_layer_weight_init(): model_cfg = dict(type='FooModel', init_cfg=[dict(type='Constant', val=1, bias=2, layer='Linear'), dict(type='Constant', val=3, bias=4, layer='Conv1d'), dict(type='Constant', val=5, bias=6, layer='Conv2d')], component1=dict(type='FooConv1d', init_cfg=dict(type='Constant', val=...
def test_override_weight_init(): model_cfg = dict(type='FooModel', init_cfg=[dict(type='Constant', val=10, bias=20, override=dict(name='reg'))], component1=dict(type='FooConv1d'), component3=dict(type='FooLinear')) model = build_from_cfg(model_cfg, FOOMODELS) model.init_weights() assert torch.equal(mo...
def test_sequential_model_weight_init(): seq_model_cfg = [dict(type='FooConv1d', init_cfg=dict(type='Constant', layer='Conv1d', val=0.0, bias=1.0)), dict(type='FooConv2d', init_cfg=dict(type='Constant', layer='Conv2d', val=2.0, bias=3.0))] layers = [build_from_cfg(cfg, COMPONENTS) for cfg in seq_model_cfg] ...
def test_modulelist_weight_init(): models_cfg = [dict(type='FooConv1d', init_cfg=dict(type='Constant', layer='Conv1d', val=0.0, bias=1.0)), dict(type='FooConv2d', init_cfg=dict(type='Constant', layer='Conv2d', val=2.0, bias=3.0))] layers = [build_from_cfg(cfg, COMPONENTS) for cfg in models_cfg] modellist ...
def test_moduledict_weight_init(): models_cfg = dict(foo_conv_1d=dict(type='FooConv1d', init_cfg=dict(type='Constant', layer='Conv1d', val=0.0, bias=1.0)), foo_conv_2d=dict(type='FooConv2d', init_cfg=dict(type='Constant', layer='Conv2d', val=2.0, bias=3.0))) layers = {name: build_from_cfg(cfg, COMPONENTS) for...
@MODULE_WRAPPERS.register_module() class DDPWrapper(object): def __init__(self, module): self.module = module
class Block(nn.Module): def __init__(self): super().__init__() self.conv = nn.Conv2d(3, 3, 1) self.norm = nn.BatchNorm2d(3)
class Model(nn.Module): def __init__(self): super().__init__() self.block = Block() self.conv = nn.Conv2d(3, 3, 1)
class Mockpavimodel(object): def __init__(self, name='fakename'): self.name = name def download(self, file): pass
def assert_tensor_equal(tensor_a, tensor_b): assert tensor_a.eq(tensor_b).all()
def test_get_state_dict(): if (torch.__version__ == 'parrots'): state_dict_keys = set(['block.conv.weight', 'block.conv.bias', 'block.norm.weight', 'block.norm.bias', 'block.norm.running_mean', 'block.norm.running_var', 'conv.weight', 'conv.bias']) else: state_dict_keys = set(['block.conv.weig...
def test_load_pavimodel_dist(): sys.modules['pavi'] = MagicMock() sys.modules['pavi.modelcloud'] = MagicMock() pavimodel = Mockpavimodel() import pavi pavi.modelcloud.get = MagicMock(return_value=pavimodel) with pytest.raises(AssertionError): _ = load_from_pavi('MyPaviFolder/checkpoint...
def test_load_checkpoint_with_prefix(): class FooModule(nn.Module): def __init__(self): super().__init__() self.linear = nn.Linear(1, 2) self.conv2d = nn.Conv2d(3, 1, 3) self.conv2d_2 = nn.Conv2d(3, 2, 3) model = FooModule() nn.init.constant_(model...
def test_load_checkpoint(): import os import re import tempfile class PrefixModel(nn.Module): def __init__(self): super().__init__() self.backbone = Model() pmodel = PrefixModel() model = Model() checkpoint_path = os.path.join(tempfile.gettempdir(), 'check...
def test_load_checkpoint_metadata(): import os import tempfile from mmcv.runner import load_checkpoint, save_checkpoint class ModelV1(nn.Module): def __init__(self): super().__init__() self.block = Block() self.conv1 = nn.Conv2d(3, 3, 1) self.c...
def test_load_classes_name(): import os import tempfile from mmcv.runner import load_checkpoint, save_checkpoint checkpoint_path = os.path.join(tempfile.gettempdir(), 'checkpoint.pth') model = Model() save_checkpoint(model, checkpoint_path) checkpoint = load_checkpoint(model, checkpoint_pa...
def test_checkpoint_loader(): import os import tempfile from mmcv.runner import CheckpointLoader, _load_checkpoint, save_checkpoint checkpoint_path = os.path.join(tempfile.gettempdir(), 'checkpoint.pth') model = Model() save_checkpoint(model, checkpoint_path) checkpoint = _load_checkpoint(...
def test_save_checkpoint(tmp_path): model = Model() optimizer = optim.SGD(model.parameters(), lr=0.1, momentum=0.9) with pytest.raises(TypeError): save_checkpoint(model, '/path/of/your/filename', meta='invalid type') filename = str((tmp_path / 'checkpoint1.pth')) save_checkpoint(model, fil...
def test_load_from_local(): import os home_path = os.path.expanduser('~') checkpoint_path = os.path.join(home_path, 'dummy_checkpoint_used_to_test_load_from_local.pth') model = Model() save_checkpoint(model, checkpoint_path) checkpoint = load_from_local('~/dummy_checkpoint_used_to_test_load_fr...
@patch('torch.cuda.device_count', return_value=1) @patch('torch.cuda.set_device') @patch('torch.distributed.init_process_group') @patch('subprocess.getoutput', return_value='127.0.0.1') def test_init_dist(mock_getoutput, mock_dist_init, mock_set_device, mock_device_count): with pytest.raises(ValueError): ...
class ExampleDataset(Dataset): def __init__(self): self.index = 0 self.eval_result = [1, 4, 3, 7, 2, (- 3), 4, 6] def __getitem__(self, idx): results = dict(x=torch.tensor([1])) return results def __len__(self): return 1 @mock.create_autospec def evaluat...
class EvalDataset(ExampleDataset): def evaluate(self, results, logger=None): acc = self.eval_result[self.index] output = OrderedDict(acc=acc, index=self.index, score=acc, loss_top=acc) self.index += 1 return output
class Model(nn.Module): def __init__(self): super().__init__() self.param = nn.Parameter(torch.tensor([1.0])) def forward(self, x, **kwargs): return (self.param * x) def train_step(self, data_batch, optimizer, **kwargs): return {'loss': torch.sum(self(data_batch['x']))} ...
def _build_epoch_runner(): model = Model() tmp_dir = tempfile.mkdtemp() runner = EpochBasedRunner(model=model, work_dir=tmp_dir, logger=get_logger('demo')) return runner
def _build_iter_runner(): model = Model() tmp_dir = tempfile.mkdtemp() runner = IterBasedRunner(model=model, work_dir=tmp_dir, logger=get_logger('demo')) return runner
class EvalHook(BaseEvalHook): _default_greater_keys = ['acc', 'top'] _default_less_keys = ['loss', 'loss_top'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs)
class DistEvalHook(BaseDistEvalHook): greater_keys = ['acc', 'top'] less_keys = ['loss', 'loss_top'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs)
def test_eval_hook(): with pytest.raises(AssertionError): test_dataset = Model() data_loader = DataLoader(test_dataset) EvalHook(data_loader, save_best=True) with pytest.raises(TypeError): test_dataset = Model() data_loader = [DataLoader(test_dataset)] EvalHook(...
@patch('mmcv.engine.single_gpu_test', MagicMock) @patch('mmcv.engine.multi_gpu_test', MagicMock) @pytest.mark.parametrize('EvalHookParam', [EvalHook, DistEvalHook]) @pytest.mark.parametrize('_build_demo_runner,by_epoch', [(_build_epoch_runner, True), (_build_iter_runner, False)]) def test_start_param(EvalHookParam, _...
@pytest.mark.parametrize('runner,by_epoch,eval_hook_priority', [(EpochBasedRunner, True, 'NORMAL'), (EpochBasedRunner, True, 'LOW'), (IterBasedRunner, False, 'LOW')]) def test_logger(runner, by_epoch, eval_hook_priority): loader = DataLoader(EvalDataset()) model = Model() data_loader = DataLoader(EvalData...
def test_cast_tensor_type(): inputs = torch.FloatTensor([5.0]) src_type = torch.float32 dst_type = torch.int32 outputs = cast_tensor_type(inputs, src_type, dst_type) assert isinstance(outputs, torch.Tensor) assert (outputs.dtype == dst_type) inputs = torch.FloatTensor([5.0]) src_type =...
def test_auto_fp16(): with pytest.raises(TypeError): class ExampleObject(object): @auto_fp16() def __call__(self, x): return x model = ExampleObject() input_x = torch.ones(1, dtype=torch.float32) model(input_x) class ExampleModule(nn.M...
def test_force_fp32(): with pytest.raises(TypeError): class ExampleObject(object): @force_fp32() def __call__(self, x): return x model = ExampleObject() input_x = torch.ones(1, dtype=torch.float32) model(input_x) class ExampleModule(nn...
def test_optimizerhook(): class Model(nn.Module): def __init__(self): super().__init__() self.conv1 = nn.Conv2d(in_channels=1, out_channels=2, kernel_size=3, stride=1, padding=1, dilation=1) self.conv2 = nn.Conv2d(in_channels=2, out_channels=2, kernel_size=3, stride=1...
def test_checkpoint_hook(tmp_path): 'xdoctest -m tests/test_runner/test_hooks.py test_checkpoint_hook.' loader = DataLoader(torch.ones((5, 2))) runner = _build_demo_runner('EpochBasedRunner', max_epochs=1) runner.meta = dict() checkpointhook = CheckpointHook(interval=1, by_epoch=True) runner.r...
def test_ema_hook(): 'xdoctest -m tests/test_hooks.py test_ema_hook.' class DemoModel(nn.Module): def __init__(self): super().__init__() self.conv = nn.Conv2d(in_channels=1, out_channels=2, kernel_size=1, padding=1, bias=True) self._init_weight() def _ini...
def test_custom_hook(): @HOOKS.register_module() class ToyHook(Hook): def __init__(self, info, *args, **kwargs): super().__init__() self.info = info runner = _build_demo_runner_without_hook('EpochBasedRunner', max_epochs=1) runner.register_custom_hooks(None) asser...
def test_pavi_hook(): sys.modules['pavi'] = MagicMock() loader = DataLoader(torch.ones((5, 2))) runner = _build_demo_runner() runner.meta = dict(config_dict=dict(lr=0.02, gpu_ids=range(1))) hook = PaviLoggerHook(add_graph=False, add_last_ckpt=True) runner.register_hook(hook) runner.run([lo...
def test_sync_buffers_hook(): loader = DataLoader(torch.ones((5, 2))) runner = _build_demo_runner() runner.register_hook_from_cfg(dict(type='SyncBuffersHook')) runner.run([loader, loader], [('train', 1), ('val', 1)]) shutil.rmtree(runner.work_dir)
@pytest.mark.parametrize('multi_optimizers, max_iters, gamma, cyclic_times', [(True, 8, 1, 1), (False, 8, 0.5, 2)]) def test_momentum_runner_hook(multi_optimizers, max_iters, gamma, cyclic_times): 'xdoctest -m tests/test_hooks.py test_momentum_runner_hook.' sys.modules['pavi'] = MagicMock() loader = DataL...
@pytest.mark.parametrize('multi_optimizers', (True, False)) def test_cosine_runner_hook(multi_optimizers): 'xdoctest -m tests/test_hooks.py test_cosine_runner_hook.' sys.modules['pavi'] = MagicMock() loader = DataLoader(torch.ones((10, 2))) runner = _build_demo_runner(multi_optimizers=multi_optimizers...
@pytest.mark.parametrize('multi_optimizers, by_epoch', [(False, False), (True, False), (False, True), (True, True)]) def test_flat_cosine_runner_hook(multi_optimizers, by_epoch): 'xdoctest -m tests/test_hooks.py test_flat_cosine_runner_hook.' sys.modules['pavi'] = MagicMock() loader = DataLoader(torch.one...
@pytest.mark.parametrize('multi_optimizers, max_iters', [(True, 10), (True, 2), (False, 10), (False, 2)]) def test_one_cycle_runner_hook(multi_optimizers, max_iters): 'Test OneCycleLrUpdaterHook and OneCycleMomentumUpdaterHook.' with pytest.raises(AssertionError): OneCycleLrUpdaterHook(max_lr=0.1, by_...
@pytest.mark.parametrize('multi_optimizers', (True, False)) def test_cosine_restart_lr_update_hook(multi_optimizers): 'Test CosineRestartLrUpdaterHook.' with pytest.raises(AssertionError): CosineRestartLrUpdaterHook(by_epoch=False, periods=[2, 10], restart_weights=[0.5, 0.5], min_lr=0.1, min_lr_ratio=...
@pytest.mark.parametrize('multi_optimizers', (True, False)) def test_step_runner_hook(multi_optimizers): 'Test StepLrUpdaterHook.' with pytest.raises(TypeError): StepLrUpdaterHook() with pytest.raises(AssertionError): StepLrUpdaterHook((- 10)) with pytest.raises(AssertionError): ...
@pytest.mark.parametrize('multi_optimizers, max_iters, gamma, cyclic_times', [(True, 8, 1, 1), (False, 8, 0.5, 2)]) def test_cyclic_lr_update_hook(multi_optimizers, max_iters, gamma, cyclic_times): 'Test CyclicLrUpdateHook.' with pytest.raises(AssertionError): CyclicLrUpdaterHook(by_epoch=True) wi...
@pytest.mark.parametrize('log_model', (True, False)) def test_mlflow_hook(log_model): sys.modules['mlflow'] = MagicMock() sys.modules['mlflow.pytorch'] = MagicMock() runner = _build_demo_runner() loader = DataLoader(torch.ones((5, 2))) hook = MlflowLoggerHook(exp_name='test', log_model=log_model) ...
def test_segmind_hook(): sys.modules['segmind'] = MagicMock() runner = _build_demo_runner() hook = SegmindLoggerHook() loader = DataLoader(torch.ones((5, 2))) runner.register_hook(hook) runner.run([loader, loader], [('train', 1), ('val', 1)]) shutil.rmtree(runner.work_dir) hook.mlflow_...
def test_wandb_hook(): sys.modules['wandb'] = MagicMock() runner = _build_demo_runner() hook = WandbLoggerHook(log_artifact=True) loader = DataLoader(torch.ones((5, 2))) runner.register_hook(hook) runner.run([loader, loader], [('train', 1), ('val', 1)]) shutil.rmtree(runner.work_dir) h...
def test_neptune_hook(): sys.modules['neptune'] = MagicMock() sys.modules['neptune.new'] = MagicMock() runner = _build_demo_runner() hook = NeptuneLoggerHook() loader = DataLoader(torch.ones((5, 2))) runner.register_hook(hook) runner.run([loader, loader], [('train', 1), ('val', 1)]) sh...
def test_dvclive_hook(): sys.modules['dvclive'] = MagicMock() runner = _build_demo_runner() hook = DvcliveLoggerHook() dvclive_mock = hook.dvclive loader = DataLoader(torch.ones((5, 2))) runner.register_hook(hook) runner.run([loader, loader], [('train', 1), ('val', 1)]) shutil.rmtree(r...
def test_dvclive_hook_model_file(tmp_path): sys.modules['dvclive'] = MagicMock() runner = _build_demo_runner() hook = DvcliveLoggerHook(model_file=osp.join(runner.work_dir, 'model.pth')) runner.register_hook(hook) loader = torch.utils.data.DataLoader(torch.ones((5, 2))) loader = DataLoader(tor...
def _build_demo_runner_without_hook(runner_type='EpochBasedRunner', max_epochs=1, max_iters=None, multi_optimizers=False): class Model(nn.Module): def __init__(self): super().__init__() self.linear = nn.Linear(2, 1) self.conv = nn.Conv2d(3, 3, 3) def forward(...
def _build_demo_runner(runner_type='EpochBasedRunner', max_epochs=1, max_iters=None, multi_optimizers=False): log_config = dict(interval=1, hooks=[dict(type='TextLoggerHook')]) runner = _build_demo_runner_without_hook(runner_type, max_epochs, max_iters, multi_optimizers) runner.register_checkpoint_hook(di...
def test_runner_with_revise_keys(): import os class Model(nn.Module): def __init__(self): super().__init__() self.conv = nn.Conv2d(3, 3, 1) class PrefixModel(nn.Module): def __init__(self): super().__init__() self.backbone = Model() p...
def test_get_triggered_stages(): class ToyHook(Hook): def before_run(): pass def after_epoch(): pass hook = ToyHook() expected_stages = ['before_run', 'after_train_epoch', 'after_val_epoch'] assert (hook.get_triggered_stages() == expected_stages)
def test_gradient_cumulative_optimizer_hook(): class ToyModel(nn.Module): def __init__(self, with_norm=False): super().__init__() self.fp16_enabled = False self.fc = nn.Linear(3, 2) nn.init.constant_(self.fc.weight, 1.0) nn.init.constant_(self....
@pytest.mark.skipif((not torch.cuda.is_available()), reason='requires CUDA support') def test_gradient_cumulative_fp16_optimizer_hook(): class ToyModel(nn.Module): def __init__(self): super().__init__() self.fp16_enabled = False self.fc = nn.Linear(3, 2) n...
class SubModel(nn.Module): def __init__(self): super().__init__() self.conv1 = nn.Conv2d(2, 2, kernel_size=1, groups=2) self.gn = nn.GroupNorm(2, 2) self.param1 = nn.Parameter(torch.ones(1)) def forward(self, x): return x
class ExampleModel(nn.Module): def __init__(self): super().__init__() self.param1 = nn.Parameter(torch.ones(1)) self.conv1 = nn.Conv2d(3, 4, kernel_size=1, bias=False) self.conv2 = nn.Conv2d(4, 2, kernel_size=1) self.bn = nn.BatchNorm2d(2) self.sub = SubModel() ...