You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

launcher.py 1.6 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2020 Megvii Inc. All rights reserved.
  5. #
  6. # Unless required by applicable law or agreed to in writing,
  7. # software distributed under the License is distributed on an
  8. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. import multiprocessing as mp
  10. from .group import init_process_group
  11. from .helper import get_device_count_by_fork
  12. from .server import Server
  13. from .util import get_free_ports
  14. def _run_wrapped(func, master_ip, port, world_size, rank, dev, args, kwargs):
  15. """Init distributed process group and run wrapped function."""
  16. init_process_group(
  17. master_ip=master_ip, port=port, world_size=world_size, rank=rank, device=dev
  18. )
  19. func(*args, **kwargs)
  20. def launcher(func):
  21. """Decorator for launching multiple processes in single-machine multi-gpu training."""
  22. n_gpus = get_device_count_by_fork("gpu")
  23. def wrapper(*args, **kwargs):
  24. master_ip = "localhost"
  25. port = get_free_ports(1)[0]
  26. server = Server(port)
  27. procs = []
  28. for rank in range(n_gpus):
  29. p = mp.Process(
  30. target=_run_wrapped,
  31. args=(func, master_ip, port, n_gpus, rank, rank, args, kwargs),
  32. )
  33. p.start()
  34. procs.append(p)
  35. for rank in range(n_gpus):
  36. procs[rank].join()
  37. code = procs[rank].exitcode
  38. assert code == 0, "subprocess {} exit with code {}".format(rank, code)
  39. return wrapper

MegEngine 安装包中集成了使用 GPU 运行代码所需的 CUDA 环境,不用区分 CPU 和 GPU 版。 如果想要运行 GPU 程序,请确保机器本身配有 GPU 硬件设备并安装好驱动。 如果你想体验在云端 GPU 算力平台进行深度学习开发的感觉,欢迎访问 MegStudio 平台