torchrun是PyTorch分布式训练命令行工具,支持单机多卡和多机多卡训练。
基本用法
1
| torchrun [options] your_script.py [args]
|
常用参数
| 参数 | 说明 |
|---|
--nnodes=N | 总节点数(默认1) |
--nproc_per_node=G | 每节点进程数(通常等于GPU数量) |
--node_rank=R | 当前节点排名(从0开始) |
--master_addr=HOST | 主节点地址(默认127.0.0.1) |
--master_port=PORT | 主节点端口(默认29500) |
--standalone | 单机模式,简化配置 |
示例
单机多卡(4 GPU):
1
| torchrun --standalone --nproc_per_node=4 your_script.py --args
|
多机多卡(2节点各4 GPU):
节点0:
1
2
| torchrun --nnodes=2 --nproc_per_node=4 --node_rank=0 \
--master_addr="node0_ip" --master_port=12345 your_script.py
|
节点1:
1
2
| torchrun --nnodes=2 --nproc_per_node=4 --node_rank=1 \
--master_addr="node0_ip" --master_port=12345 your_script.py
|
脚本配置
1
2
3
4
5
6
7
8
9
10
11
| import torch
import torch.distributed as dist
def main():
dist.init_process_group(backend="nccl")
local_rank = int(os.environ["LOCAL_RANK"])
torch.cuda.set_device(local_rank)
# 创建分布式数据加载器和模型...
if __name__ == "__main__":
main()
|
注意事项
- 使用
--standalone时无需设置master_addr和node_rank - 确保所有节点间网络互通
- 脚本需兼容分布式训练(使用
DistributedDataLoader)
Comments