CentOS 与 PyTorch 网络通信问题排查与解决
一 基础连通性排查
- 确认网卡与 IP:使用命令查看接口与地址,例如:ip addr;传统 ifconfig 若未安装,可执行:sudo yum install -y net-tools。
- 检查默认路由与 DNS:查看路由表:ip route;查看 DNS 配置:cat /etc/resolv.conf。
- 连通性测试:先 ping 网关(见 ip route 的 default via),再 ping 外网地址(如 8.8.8.8),最后测试域名解析(如 nslookup www.baidu.com)。
- 常见现象与处理:最小化安装可能缺少 ping(iputils-ping),安装即可;网卡名在 CentOS 7+ 可能为 ens33/enp0s3 等新命名。
以上步骤可快速定位是否为网络层问题,为后续 PyTorch 下载与分布式通信打基础。
二 代理与软件源配置
- 若处于公司/校园网,需要配置代理(对当前会话生效):
- 临时导出:export http_proxy=http://[地址]:[端口] https_proxy=http://[地址]:[端口]
- 永久生效:写入 /etc/profile 或 ~/.bashrc,然后 source /etc/profile。
- 使用国内镜像加速 pip 安装(解决超时/不稳定):
- 示例:pip --default-timeout=100 install torch -i https://pypi.tuna.tsinghua.edu.cn/simple/
- 使用国内镜像加速 conda 安装:
- 添加清华通道:
- conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
- conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge/
- conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/pytorch/
- 查看与精简通道:conda config --show channels;必要时移除 defaults 以避免回源官方库。
- 常见现象与处理:pip 报 Timeout 换镜像与延长超时;报 Hash 值不匹配 多为下载不完整,重试或更换镜像;conda 换源后仍慢或失败,检查是否命中 defaults 通道。
上述方法可显著提升在受限网络环境下安装 PyTorch 的成功率与速度。
三 防火墙与安全组策略
- 本机防火墙(firewalld):训练/推理常需开放端口(如 TCP 22/80/443 或自定义端口)。示例:
- 查看状态:sudo firewall-cmd --state
- 放行端口:sudo firewall-cmd --permanent --add-port=12345/tcp
- 重新加载:sudo firewall-cmd --reload
- 云服务器安全组:在控制台放行对应 入站/出站 端口(协议、端口范围、源/目的网段)。
- 企业/校园网策略:可能限制对外端口或限制 pip/conda 域名访问,需联系网管或使用镜像源/离线安装。
- 分布式训练提示:如使用 gloo/tcp 后端,确保节点间相应端口互通;如使用 nccl 后端,还需保证 GPU 驱动与 NCCL 正常、网络低丢包。
防火墙与安全组是分布式训练与远程访问最常见的阻断点,需优先排查。
四 PyTorch 分布式与数据通信实践
- 环境验证:在 Python 中确认版本与设备可用性
- import torch; print(torch.version); print(torch.cuda.is_available())
- 启动方式示例:
- 单机多卡(GPU):torchrun --nproc_per_node=2 train.py
- 多机多卡:在每台机器上设置 MASTER_ADDR/MASTER_PORT,例如:
- 节点0:export MASTER_ADDR=192.168.1.10; export MASTER_PORT=12345
- 节点1:export MASTER_ADDR=192.168.1.10; export MASTER_PORT=12345
- 然后各节点执行:torchrun --nproc_per_node=2 --nnodes=2 --node_rank=0/1 train.py
- 常见问题与处理:
- 报错 “由于目标计算机积极拒绝,无法连接”:多为目标端口未监听/被防火墙拦截/安全组未放行,或 master 地址/端口配置错误;检查监听与连通性后重试。
- 下载依赖慢或失败:切换 pip/conda 镜像、延长 timeout、必要时使用离线包。
- 内存不足导致安装失败:使用 pip install torch --no-cache-dir 降低内存占用。
以上步骤覆盖 PyTorch 安装、单机多卡与多机多卡的常见网络问题定位与处理。