Launch multi-gpu or distributed training. This function must be called on all machines involved in the training. It will spawn child processes (defined by ``num_gpus_per_machine``) on each machine. Args: main_func: a function that will be called by `main_func(*args)`
(main_func, num_gpus_per_machine, num_machines=1, machine_rank=0, dist_url=None, args=())
| 22 | |
| 23 | |
| 24 | def launch(main_func, num_gpus_per_machine, num_machines=1, machine_rank=0, dist_url=None, args=()): |
| 25 | """ |
| 26 | Launch multi-gpu or distributed training. |
| 27 | This function must be called on all machines involved in the training. |
| 28 | It will spawn child processes (defined by ``num_gpus_per_machine``) on each machine. |
| 29 | |
| 30 | Args: |
| 31 | main_func: a function that will be called by `main_func(*args)` |
| 32 | num_gpus_per_machine (int): number of GPUs per machine |
| 33 | num_machines (int): the total number of machines |
| 34 | machine_rank (int): the rank of this machine |
| 35 | dist_url (str): url to connect to for distributed jobs, including protocol |
| 36 | e.g. "tcp://127.0.0.1:8686". |
| 37 | Can be set to "auto" to automatically select a free port on localhost |
| 38 | args (tuple): arguments passed to main_func |
| 39 | """ |
| 40 | world_size = num_machines * num_gpus_per_machine |
| 41 | if world_size > 1: |
| 42 | # https://github.com/pytorch/pytorch/pull/14391 |
| 43 | # TODO prctl in spawned processes |
| 44 | |
| 45 | if dist_url == "auto": |
| 46 | assert num_machines == 1, "dist_url=auto not supported in multi-machine jobs." |
| 47 | port = _find_free_port() |
| 48 | dist_url = f"tcp://127.0.0.1:{port}" |
| 49 | if num_machines > 1 and dist_url.startswith("file://"): |
| 50 | logger = logging.getLogger(__name__) |
| 51 | logger.warning( |
| 52 | "file:// is not a reliable init_method in multi-machine jobs. Prefer tcp://" |
| 53 | ) |
| 54 | |
| 55 | mp.spawn( |
| 56 | _distributed_worker, |
| 57 | nprocs=num_gpus_per_machine, |
| 58 | args=(main_func, world_size, num_gpus_per_machine, machine_rank, dist_url, args), |
| 59 | daemon=False, |
| 60 | ) |
| 61 | else: |
| 62 | main_func(*args) |
| 63 | |
| 64 | |
| 65 | def _distributed_worker( |
no test coverage detected