dist.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. # Ultralytics YOLO 🚀, AGPL-3.0 license
  2. import os
  3. import re
  4. import shutil
  5. import socket
  6. import sys
  7. import tempfile
  8. from pathlib import Path
  9. from . import USER_CONFIG_DIR
  10. from .torch_utils import TORCH_1_9
  11. def find_free_network_port() -> int:
  12. """Finds a free port on localhost.
  13. It is useful in single-node training when we don't want to connect to a real main node but have to set the
  14. `MASTER_PORT` environment variable.
  15. """
  16. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
  17. s.bind(('127.0.0.1', 0))
  18. return s.getsockname()[1] # port
  19. def generate_ddp_file(trainer):
  20. """Generates a DDP file and returns its file name."""
  21. module, name = f'{trainer.__class__.__module__}.{trainer.__class__.__name__}'.rsplit('.', 1)
  22. content = f'''overrides = {vars(trainer.args)} \nif __name__ == "__main__":
  23. from {module} import {name}
  24. from ultralytics.utils import DEFAULT_CFG_DICT
  25. cfg = DEFAULT_CFG_DICT.copy()
  26. cfg.update(save_dir='') # handle the extra key 'save_dir'
  27. trainer = {name}(cfg=cfg, overrides=overrides)
  28. trainer.train()'''
  29. (USER_CONFIG_DIR / 'DDP').mkdir(exist_ok=True)
  30. with tempfile.NamedTemporaryFile(prefix='_temp_',
  31. suffix=f'{id(trainer)}.py',
  32. mode='w+',
  33. encoding='utf-8',
  34. dir=USER_CONFIG_DIR / 'DDP',
  35. delete=False) as file:
  36. file.write(content)
  37. return file.name
  38. def generate_ddp_command(world_size, trainer):
  39. """Generates and returns command for distributed training."""
  40. import __main__ # noqa local import to avoid https://github.com/Lightning-AI/lightning/issues/15218
  41. if not trainer.resume:
  42. shutil.rmtree(trainer.save_dir) # remove the save_dir
  43. file = str(Path(sys.argv[0]).resolve())
  44. safe_pattern = re.compile(r'^[a-zA-Z0-9_. /\\-]{1,128}$') # allowed characters and maximum of 100 characters
  45. if not (safe_pattern.match(file) and Path(file).exists() and file.endswith('.py')): # using CLI
  46. file = generate_ddp_file(trainer)
  47. dist_cmd = 'torch.distributed.run' if TORCH_1_9 else 'torch.distributed.launch'
  48. port = find_free_network_port()
  49. cmd = [sys.executable, '-m', dist_cmd, '--nproc_per_node', f'{world_size}', '--master_port', f'{port}', file]
  50. return cmd, file
  51. def ddp_cleanup(trainer, file):
  52. """Delete temp file if created."""
  53. if f'{id(trainer)}.py' in file: # if temp_file suffix in file
  54. os.remove(file)