vscode 的 ddp 调试
ide
本文字数:674 字 | 阅读时长 ≈ 3 min

vscode 的 ddp 调试

ide
本文字数:674 字 | 阅读时长 ≈ 3 min

1. torch.distributed.launch

在 PyTorch 中,如果我们要运行一个分布式的程序会用到以下命令 python -m torch.distributed.launch --nproc_per_node 8 train.py

但是如果我们想调试的时候如果使用命令行调试就会很麻烦,这里我们需要用到 vscode 的 launch.json 调试方法,首先我们打开 vscode,看一下文件目录下有没有 .vscode 目录,如果有看一下里面有没有 launch.json 文件,如果没有我们需要新建一下,如下所示,依次点击

然后选择相应的 python 调试文件即可,此时会生成一个 launch.json 文件,内容如下所示

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal"
        }
    ]
}

然后我们将其进行修改,我们采用单卡调试,也就是说我们的调试要达到一下命令的效果 python -m torch.distributed.launch --nproc_per_node 1 train.py

下面是修改后的文件,其中 program 是我们要运行的文件,就是 launch.py,然后 -m 参数忽略即可,args 是我们后续的参数,有 --nproc_per_node 1 以及 train.py,如果要多卡调试就将 1 改为你需要的卡数即可

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: 当前文件",
            "type": "python",
            "request": "launch",
            "program": "/home/wangyh/anaconda3/envs/torch/lib/python3.6/site-packages/torch/distributed/launch.py",
            "console": "integratedTerminal",
            "args": [
                "--nproc_per_node=1",
                "train.py",
            ],
            "env": {"CUDA_VISIBLE_DEVICES":"0"},
        }
    ]
}

注意:调试的时候点击下面图片的绿色三角才能进行调试!!!!!!如果点击插件 run 中的 debug in terminal 是不能进行调试的!!!好了到这里就可以开心的调试啦

2. torchrun

在 pytorch 的新版本 torch.distributed.launch 被舍弃了,采用 torchrun 来分布式执行,只需要将 program 处修改一下即可

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python Debugger: Current File",
            "type": "debugpy",
            "request": "launch",
            "program": "/home/wangyh/miniconda3/envs/timechat/lib/python3.10/site-packages/torch/distributed/run.py",
            "console": "integratedTerminal",
            "args": [
                "--nproc_per_node=1",
                "train.py",
                "--num_workers", "1",
            ],
            "env": {"CUDA_VISIBLE_DEVICES":"0"},
        }
    ]
}
4月 06, 2025
3月 10, 2025
12月 31, 2024