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
(model, data_loader, tmpdir=None, gpu_collect=False)
| 35 | |
| 36 | |
| 37 | def multi_gpu_test(model, data_loader, tmpdir=None, gpu_collect=False): |
| 38 | """Test model with multiple gpus. |
| 39 | This method tests model with multiple gpus and collects the results |
| 40 | under two different modes: gpu and cpu modes. By setting 'gpu_collect=True' |
| 41 | it encodes results to gpu tensors and use gpu communication for results |
| 42 | collection. On cpu mode it saves the results on different gpus to 'tmpdir' |
| 43 | and collects them by the rank 0 worker. |
| 44 | Args: |
| 45 | model (nn.Module): Model to be tested. |
| 46 | data_loader (nn.Dataloader): Pytorch data loader. |
| 47 | tmpdir (str): Path of directory to save the temporary results from |
| 48 | different gpus under cpu mode. |
| 49 | gpu_collect (bool): Option to use either gpu or cpu to collect results. |
| 50 | Returns: |
| 51 | list: The prediction results. |
| 52 | """ |
| 53 | model.eval() |
| 54 | results = [] |
| 55 | dataset = data_loader.dataset |
| 56 | rank, world_size = get_dist_info() |
| 57 | if rank == 0: |
| 58 | # Check if tmpdir is valid for cpu_collect |
| 59 | if (not gpu_collect) and (tmpdir is not None and osp.exists(tmpdir)): |
| 60 | raise OSError((f'The tmpdir {tmpdir} already exists.', |
| 61 | ' Since tmpdir will be deleted after testing,', |
| 62 | ' please make sure you specify an empty one.')) |
| 63 | prog_bar = mmcv.ProgressBar(len(dataset)) |
| 64 | time.sleep(2) # This line can prevent deadlock problem in some cases. |
| 65 | for i, data in enumerate(data_loader): |
| 66 | with torch.no_grad(): |
| 67 | result = model(return_loss=False, **data) |
| 68 | if isinstance(result, list): |
| 69 | results.extend(result) |
| 70 | else: |
| 71 | results.append(result) |
| 72 | |
| 73 | if rank == 0: |
| 74 | batch_size = data['motion'].size(0) |
| 75 | for _ in range(batch_size * world_size): |
| 76 | prog_bar.update() |
| 77 | |
| 78 | # collect results from all ranks |
| 79 | if gpu_collect: |
| 80 | results = collect_results_gpu(results, len(dataset)) |
| 81 | else: |
| 82 | results = collect_results_cpu(results, len(dataset), tmpdir) |
| 83 | return results |
| 84 | |
| 85 | |
| 86 | def collect_results_cpu(result_part, size, tmpdir=None): |
no test coverage detected