def run_training(script_name, config_name, cudnn_benchmark=True, local_rank=-1, save_dir=None, base_seed=None,
use_lmdb=False, script_name_prv=None, config_name_prv=None, use_wandb=False,
distill=None, script_teacher=None, config_teacher=None):
"""Run the train script.
args:
script_name: Name of emperiment in the "experiments/" folder.
config_name: Name of the yaml file in the "experiments/<script_name>".
cudnn_benchmark: Use cudnn benchmark or not (default is True).
"""
if save_dir is None:
print("save_dir dir is not given. Use the default dir instead.")
# This is needed to avoid strange crashes related to opencv
cv.setNumThreads(0)
torch.backends.cudnn.benchmark = cudnn_benchmark
print('script_name: {}.py config_name: {}.yaml'.format(script_name, config_name))
'''2021.1.5 set seed for different process'''
if base_seed is not None:
if local_rank != -1:
init_seeds(base_seed + local_rank)
else:
init_seeds(base_seed)
settings = ws_settings.Settings()
settings.script_name = script_name
settings.config_name = config_name
settings.project_path = 'train/{}/{}'.format(script_name, config_name)
if script_name_prv is not None and config_name_prv is not None:
settings.project_path_prv = 'train/{}/{}'.format(script_name_prv, config_name_prv)
settings.local_rank = local_rank
settings.save_dir = os.path.abspath(save_dir)
settings.use_lmdb = use_lmdb
prj_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "../.."))
settings.cfg_file = os.path.join(prj_dir, 'experiments/%s/%s.yaml' % (script_name, config_name))
settings.use_wandb = use_wandb
if distill:
settings.distill = distill
settings.script_teacher = script_teacher
settings.config_teacher = config_teacher
if script_teacher is not None and config_teacher is not None:
settings.project_path_teacher = 'train/{}/{}'.format(script_teacher, config_teacher)
settings.cfg_file_teacher = os.path.join(prj_dir, 'experiments/%s/%s.yaml' % (script_teacher, config_teacher))
expr_module = importlib.import_module('lib.train.train_script_distill')
else:
expr_module = importlib.import_module('lib.train.train_script')
expr_func = getattr(expr_module, 'run')
expr_func(settings)
def main():
parser = argparse.ArgumentParser(description='Run a train scripts in train_settings.')
parser.add_argument('--script', type=str, required=True, help='Name of the train script.')
parser.add_argument('--config', type=str, required=True, help="Name of the config file.")
parser.add_argument('--cudnn_benchmark', type=bool, default=True, help='Set cudnn benchmark on (1) or off (0) (default is on).')
# parser.add_argument('--local_rank', default=-1, type=int, help='node rank for distributed training')
parser.add_argument('--save_dir', type=str, help='the directory to save checkpoints and logs')
parser.add_argument('--seed', type=int, default=3407, help='seed for random numbers, default=42')
parser.add_argument('--use_lmdb', type=int, choices=[0, 1], default=0) # whether datasets are in lmdb format
parser.add_argument('--script_prv', type=str, default=None, help='Name of the train script of previous model.')
parser.add_argument('--config_prv', type=str, default=None, help="Name of the config file of previous model.")
parser.add_argument('--use_wandb', type=int, choices=[0, 1], default=0) # whether to use wandb
# for knowledge distillation
parser.add_argument('--distill', type=int, choices=[0, 1], default=0) # whether to use knowledge distillation
parser.add_argument('--script_teacher', type=str, help='teacher script name')
parser.add_argument('--config_teacher', type=str, help='teacher yaml configure file name')
import torch
print("Available CUDA devices:", torch.cuda.device_count())
print("CUDA_VISIBLE_DEVICES:", os.environ["CUDA_VISIBLE_DEVICES"])
User
报错:6, in main
run(args)
File "/home/heyuting/anaconda3/envs/mamba/lib/python3.10/site-packages/torch/distributed/run.py", line 797, in run
elastic_launch(
File "/home/heyuting/anaconda3/envs/mamba/lib/python3.10/site-packages/torch/distributed/launcher/api.py", line 134, in call
return launch_agent(self._config, self._entrypoint, list(args))
File "/home/heyuting/anaconda3/envs/mamba/lib/python3.10/site-packages/torch/distributed/launcher/api.py", line 255, in launch_agent
result = agent.run()
File "/home/heyuting/anaconda3/envs/mamba/lib/python3.10/site-packages/torch/distributed/elastic/metrics/api.py", line 124, in wrapper
result = f(*args, **kwargs)
File "/home/heyuting/anaconda3/envs/mamba/lib/python3.10/site-packages/torch/distributed/elastic/agent/server/api.py", line 736, in run
result = self._invoke_run(role)
File "/home/heyuting/anaconda3/envs/mamba/lib/python3.10/site-packages/torch/distributed/elastic/agent/server/api.py", line 871, in _invoke_run
self._initialize_workers(self._worker_group)
File "/home/heyuting/anaconda3/envs/mamba/lib/python3.10/site-packages/torch/distributed/elastic/metrics/api.py", line 124, in wrapper
result = f(*args, **kwargs)
File "/home/heyuting/anaconda3/envs/mamba/lib/python3.10/site-packages/torch/distributed/elastic/agent/server/api.py", line 705, in _initialize_workers
self._rendezvous(worker_group)
File "/home/heyuting/anaconda3/envs/mamba/lib/python3.10/site-packages/torch/distributed/elastic/metrics/api.py", line 124, in wrapper
result = f(*args, **kwargs)
File "/home/heyuting/anaconda3/envs/mamba/lib/python3.10/site-packages/torch/distributed/elastic/agent/server/api.py", line 546, in _rendezvous
store, group_rank, group_world_size = spec.rdzv_handler.next_rendezvous()
File "/home/heyuting/anaconda3/envs/mamba/lib/python3.10/site-packages/torch/distributed/elastic/rendezvous/static_tcp_rendezvous.py", line 54, in next_rendezvous
self._store = TCPStore( # type: ignore[call-arg]
RuntimeError: The server socket has failed to listen on any local network address. The server socket has failed to bind to [::]:29500 (errno: 98 - Address already in use). The server socket has failed to bind to 0.0.0.0:29500 (errno: 98 - Address already in use).
Assistant
这个错误 Address already in use 表明端口 29500 已经被某个进程占用。PyTorch 的分布式训练框架需要使用一个固定的端口进行多进程之间的通信,如果这个端口被占用了,就会出现这个错误。
if name == 'main':
# os.environ['CUDA_VISIBLE_DEVICES'] = "4"
main()
和 ② import os
import argparse
import random
def parse_args():
"""
args for training.
"""
parser = argparse.ArgumentParser(description='Parse args for training')
# for train
parser.add_argument('--script', type=str, help='training script name')
parser.add_argument('--config', type=str, default='baseline', help='yaml configure file name')
parser.add_argument('--save_dir', type=str, help='root directory to save checkpoints, logs, and tensorboard')
parser.add_argument('--mode', type=str, choices=["single", "multiple", "multi_node"], default="multiple",
help="train on single gpu or multiple gpus")
# parser.add_argument('--nproc_per_node', type=int, help="number of GPUs per node") # specify when mode is multiple
parser.add_argument('--nproc_per_node', type=int, default=1, help="number of GPUs per node")
parser.add_argument('--use_lmdb', type=int, choices=[0, 1], default=0) # whether datasets are in lmdb format
parser.add_argument('--script_prv', type=str, help='training script name')
parser.add_argument('--config_prv', type=str, default='baseline', help='yaml configure file name')
parser.add_argument('--use_wandb', type=int, choices=[0, 1], default=0) # whether to use wandb
# for knowledge distillation
parser.add_argument('--distill', type=int, choices=[0, 1], default=0) # whether to use knowledge distillation
parser.add_argument('--script_teacher', type=str, help='teacher script name')
parser.add_argument('--config_teacher', type=str, help='teacher yaml configure file name')
# for multiple machines
parser.add_argument('--rank', type=int, help='Rank of the current process.')
parser.add_argument('--world-size', type=int, help='Number of processes participating in the job.')
parser.add_argument('--ip', type=str, default='127.0.0.1', help='IP of the current rank 0.')
parser.add_argument('--port', type=int, default='20000', help='Port of the current rank 0.')
args = parser.parse_args()
return args
if 'LOCAL_RANK' in os.environ:
args.local_rank = int(os.environ['LOCAL_RANK'])
else:
args.local_rank = 0 # 或者其他逻辑
# 添加调试信息
print(f"Process rank {args.local_rank} is using GPU {args.local_rank}")
if args.local_rank != -1:
dist.init_process_group(backend='nccl')
torch.cuda.set_device(args.local_rank)
# 再次确认
print(f"Process rank {args.local_rank} is successfully set to CUDA device {args.local_rank}")
else:
torch.cuda.set_device(0) # 默认设备设置为0