分布式通信包 - torch.distributed¶
注意
请参阅PyTorch 分布式概述 ,以获取有关分布式训练所有功能的简要介绍。
后端¶
torch.distributed 支持三种内置后端,每种后端具有不同的功能。下表显示了哪些函数可用于 CPU / CUDA 张量。
如果用于构建 PyTorch 的实现支持 CUDA,则 MPI 仅支持 CUDA。
后端 |
|
|
|
|||
|---|---|---|---|---|---|---|
设备 |
CPU |
GPU |
CPU |
GPU |
CPU |
GPU |
发送 |
✓ |
✘ |
✓ |
? |
✘ |
✓ |
接收 |
✓ |
✘ |
✓ |
? |
✘ |
✓ |
广播 |
✓ |
✓ |
✓ |
? |
✘ |
✓ |
all_reduce |
✓ |
✓ |
✓ |
? |
✘ |
✓ |
减少 |
✓ |
✘ |
✓ |
? |
✘ |
✓ |
all_gather |
✓ |
✘ |
✓ |
? |
✘ |
✓ |
聚集 |
✓ |
✘ |
✓ |
? |
✘ |
✓ |
分散 |
✓ |
✘ |
✓ |
? |
✘ |
✓ |
reduce_scatter |
✘ |
✘ |
✘ |
✘ |
✘ |
✓ |
all_to_all |
✘ |
✘ |
✓ |
? |
✘ |
✓ |
屏障 |
✓ |
✘ |
✓ |
? |
✘ |
✓ |
随PyTorch一起提供的后端¶
PyTorch 分布式包支持 Linux(稳定版)、MacOS(稳定版)和 Windows(原型)。默认情况下,对于 Linux,Gloo 和 NCCL 后端会构建并包含在 PyTorch 分布式中(仅在使用 CUDA 构建时包含 NCCL)。MPI 是一个可选的后端,只有在从源代码构建 PyTorch 时才能包含。例如,在已安装 MPI 的主机上构建 PyTorch。
注意
截至PyTorch v1.8,Windows支持所有集体通信后端,但不包括NCCL,
如果init_process_group()的init_method参数指向一个文件,则必须遵循以下模式:
本地文件系统,
init_method="file:///d:/tmp/some_file"共享文件系统,
init_method="file://////{machine_name}/{share_folder_name}/some_file"
与在Linux平台上的操作相同,您可以通过设置环境变量MASTER_ADDR和MASTER_PORT来启用TcpStore。
使用哪个后端?¶
在过去,我们经常被问到:“我应该使用哪个后端?”。
经验法则
使用NCCL后端进行分布式 GPU 训练
使用Gloo后端进行分布式 CPU 训练。
带有InfiniBand互连的GPU主机
使用NCCL,因为它是目前唯一支持InfiniBand和GPUDirect的后端。
带有以太网互联的GPU主机
使用NCCL,因为它目前提供了最佳的分布式GPU训练性能,特别是在多进程单节点或跨节点分布式训练中。如果你在使用NCCL时遇到任何问题,请使用Gloo作为备选方案。(请注意,目前Gloo在GPU上的运行速度比NCCL慢。)
带有InfiniBand互连的CPU主机
如果你的InfiniBand启用了IP over IB,请使用Gloo,否则, 请使用MPI。我们计划在未来的版本中为 Gloo添加InfiniBand支持。
带有以太网互联的CPU主机
使用Gloo,除非你有特定的理由使用MPI。
常见环境变量¶
选择要使用的网络接口¶
默认情况下,NCCL 和 Gloo 后端都会尝试找到正确的网络接口来使用。 如果自动检测到的接口不正确,您可以使用以下环境变量(适用于相应的后端)进行覆盖:
NCCL_SOCKET_IFNAME, 例如
export NCCL_SOCKET_IFNAME=eth0GLOO_SOCKET_IFNAME, 例如
export GLOO_SOCKET_IFNAME=eth0
如果你使用的是Gloo后端,可以通过用逗号分隔来指定多个接口,如下所示: export GLOO_SOCKET_IFNAME=eth0,eth1,eth2,eth3。
后端将以轮询方式在这些接口之间分发操作。
所有进程必须在此变量中指定相同数量的接口,这是至关重要的。
其他NCCL环境变量¶
调试 - 如果发生NCCL故障,您可以将 NCCL_DEBUG=INFO 设置为打印明确的警告消息以及基本的NCCL初始化信息。
您还可以使用 NCCL_DEBUG_SUBSYS 来获取有关NCCL特定方面的更多详细信息。例如,NCCL_DEBUG_SUBSYS=COLL 会打印集体调用的日志,这在调试挂起时可能很有帮助,特别是那些由集体类型或消息大小不匹配引起的挂起。如果拓扑检测失败,将 NCCL_DEBUG_SUBSYS=GRAPH 设置为检查详细的检测结果并保存以供参考可能会有所帮助,如果需要NCCL团队的进一步帮助。
性能调优 - NCCL 根据其拓扑检测自动进行调优,以节省用户的调优工作。在某些基于套接字的系统上,用户仍可能尝试调整 NCCL_SOCKET_NTHREADS 和 NCCL_NSOCKS_PERTHREAD 以增加套接字网络带宽。这两个环境变量已被 NCCL 预先为一些云提供商(如 AWS 或 GCP)进行了调优。
有关 NCCL 环境变量的完整列表,请参阅 NVIDIA NCCL 官方文档
基础¶
The torch.distributed 包提供了 PyTorch 支持和通信原语,用于在一台或多台机器上的多个计算节点之间实现多进程并行。类 torch.nn.parallel.DistributedDataParallel() 基于此功能,作为任何 PyTorch 模型的包装器,提供同步分布式训练。这与 多进程包 - torch.multiprocessing 和 torch.nn.DataParallel() 提供的并行类型不同,因为它支持多个网络连接的机器,并且用户必须为每个进程显式启动一个单独的主训练脚本副本。
在单机同步情况下,torch.distributed 或者 torch.nn.parallel.DistributedDataParallel() 包装器可能仍然比其他
数据并行方法具有优势,包括 torch.nn.DataParallel():
每个进程维护自己的优化器,并在每次迭代中执行一个完整的优化步骤。虽然这可能看起来是多余的,因为梯度已经被收集并跨进程平均,因此对每个进程来说都是相同的,但这意味着不需要参数广播步骤,减少了在节点之间传输张量所花费的时间。
每个进程包含一个独立的Python解释器,消除了从单个Python进程驱动多个执行线程、模型副本或GPU时产生的额外解释器开销和“GIL-thrashing”。这对于大量使用Python运行时的模型尤为重要,包括具有循环层或许多小组件的模型。
初始化¶
在调用任何其他方法之前,需要使用 torch.distributed.init_process_group()
函数进行初始化。这会阻塞直到所有进程都已加入。
- torch.distributed.is_available()[source]¶
如果分布式包可用,则返回
True。否则,torch.distributed不会暴露任何其他 API。目前,torch.distributed可在 Linux、MacOS 和 Windows 上使用。设置USE_DISTRIBUTED=1以在从源代码构建 PyTorch 时启用它。 目前,Linux 和 Windows 的默认值为USE_DISTRIBUTED=1, MacOS 的默认值为USE_DISTRIBUTED=0。- Return type:
- torch.distributed.init_process_group(backend=None, init_method=None, timeout=datetime.timedelta(seconds=1800), world_size=- 1, rank=- 1, store=None, group_name='', pg_options=None)[source]¶
初始化默认的分布式进程组,这也将初始化分布式包。
- There are 2 main ways to initialize a process group:
明确指定
store、rank和world_size。指定
init_method(一个URL字符串),指示在哪里/如何 发现对等节点。可选地指定rank和world_size, 或将所有必需的参数编码在URL中并省略它们。
如果两者都没有指定,则假定
init_method为“env://”。- Parameters:
后端 (str 或 Backend, 可选) – 要使用的后端。根据 构建时的配置,有效值包括
mpi,gloo,nccl和ucc。如果未提供后端,则会创建一个gloo和nccl后端,有关如何管理多个 后端的详细信息,请参见下面的注意事项。此字段可以作为小写字符串 提供(例如,"gloo"),也可以通过Backend属性访问 (例如,Backend.GLOO)。如果使用nccl后端在每台机器上运行多个进程,则每个进程 必须独占访问其使用的每个 GPU,因为在进程之间共享 GPU 可能导致死锁。ucc后端是 实验性的。init_method (str, 可选) – 指定如何初始化进程组的URL。默认情况下,如果未指定
init_method或store,则为“env://”。与store互斥。world_size (int, 可选) – 参与任务的进程数量。如果指定了
store,则为必填项。排名 (int, 可选) – 当前进程的排名(应为0到
world_size-1之间的数字)。 如果指定了store,则为必填项。存储 (存储, 可选) – 所有工作者均可访问的键/值存储,用于交换连接/地址信息。 与
init_method互斥。超时 (timedelta, 可选) – 针对进程组执行操作的超时时间。默认值等于30分钟。 这适用于
gloo后端。对于nccl,只有当环境变量NCCL_BLOCKING_WAIT或NCCL_ASYNC_ERROR_HANDLING设置为 1 时才适用。当NCCL_BLOCKING_WAIT被设置时,这是进程在抛出异常之前阻塞并等待集体操作完成的时间长度。当NCCL_ASYNC_ERROR_HANDLING被设置时, 这是集体操作被异步中止后的时间长度,之后进程将崩溃。NCCL_BLOCKING_WAIT会向用户提供可以捕获和处理的错误,但由于其阻塞性质,它有性能开销。另一方面,NCCL_ASYNC_ERROR_HANDLING的性能开销非常小,但在发生错误时会导致进程崩溃。这是因为 CUDA 执行是异步的,并且由于失败的异步 NCCL 操作可能导致后续的 CUDA 操作在损坏的数据上运行,因此不再安全地继续执行用户代码。这两个环境变量中只能设置一个。对于ucc,支持类似于 NCCL 的阻塞等待。然而,异步错误处理的方式不同,因为使用 UCC 时我们有进度线程而不是看门狗线程。group_name (str, 可选, 已弃用) – 组名。
pg_options (ProcessGroupOptions, 可选) – 进程组选项 指定在构建特定进程组时需要传递的其他选项。目前,我们唯一支持的选项是
ProcessGroupNCCL.Options用于nccl后端,is_high_priority_stream可以指定以便 当有计算内核等待时,nccl 后端可以拾取高优先级的 cuda 流。
注意
要启用
backend == Backend.MPI,需要在支持MPI的系统上从源代码构建PyTorch。注意
对多个后端的支持是实验性的。当前,如果没有指定后端,则将创建
gloo和nccl后端。gloo后端 将用于具有CPU张量的集合操作,而nccl后端将用于 具有CUDA张量的集合操作。可以通过传递格式为“<device_type>:<backend_name>,<device_type>:<backend_name>”的字符串来指定自定义后端,例如 “cpu:gloo,cuda:custom_backend”。
- torch.distributed.is_torchelastic_launched()[source]¶
检查此进程是否使用
torch.distributed.elastic(即 torchelastic)启动。通过是否存在TORCHELASTIC_RUN_ID环境 变量来判断当前进程是否使用 torchelastic 启动。这是一个合理的代理方式,因为TORCHELASTIC_RUN_ID映射到 rendezvous id,该值始终为非空值,用于表示作业 ID 以便对等发现。- Return type:
目前支持三种初始化方法:
TCP初始化¶
有两种方法可以使用TCP进行初始化,都需要一个所有进程都可以访问的网络地址和一个期望的world_size。第一种方法需要指定一个属于秩为0的进程的地址。这种初始化方法要求所有进程都手动指定了秩。
请注意,最新的分布式包中不再支持多播地址。group_name 也被弃用了。
import torch.distributed as dist
# Use address of one of the machines
dist.init_process_group(backend, init_method='tcp://10.1.1.20:23456',
rank=args.rank, world_size=4)
环境变量初始化¶
此方法将从环境变量中读取配置,允许完全自定义信息的获取方式。需要设置的变量为:
MASTER_PORT- 必需;必须是排名为0的机器上的空闲端口MASTER_ADDR- 必需(除了秩为0的节点);秩为0节点的地址WORLD_SIZE- 必需;可以在此处设置,也可以在调用初始化函数时设置RANK- 必需;可以在此处设置,也可以在调用初始化函数时设置
排名为0的机器将用于设置所有连接。
这是默认方法,这意味着 init_method 不需要指定(或者
可以是 env://)。
Post-Initialization¶
一旦运行了 torch.distributed.init_process_group(),就可以使用以下函数。要检查进程组是否已经初始化,请使用 torch.distributed.is_initialized()。
- class torch.distributed.Backend(name)[source]¶
一个类似枚举的可用后端类:GLOO、NCCL、UCC、MPI 和其他已注册的 后端。
这个类的值是小写字符串,例如,
"gloo"。它们可以通过属性访问,例如,Backend.NCCL。这个类可以直接调用来解析字符串,例如,
Backend(backend_str)将检查backend_str是否有效,并 如果有效则返回解析后的小写字符串。它还接受大写字符串, 例如,Backend("GLOO")返回"gloo"。注意
条目
Backend.UNDEFINED存在,但仅用作某些字段的初始值。用户不应直接使用它,也不应假设其存在。
- torch.distributed.get_backend(group=None)[source]¶
返回给定进程组的后端。
- Parameters:
组 (进程组, 可选) – 要工作的进程组。默认是通用主进程组。如果指定了另一个特定的组,则调用进程必须是
group的一部分。- Returns:
给定进程组的后端作为一个小写字符串。
- Return type:
分布式键值存储¶
分布式包附带了一个分布式键值存储,可以用于在组中的进程之间共享信息以及初始化分布式包在
torch.distributed.init_process_group()(通过显式创建存储作为指定init_method的替代方案。)有3种选择用于键值存储:TCPStore,
FileStore, 和 HashStore。
- class torch.distributed.TCPStore¶
基于TCP的分布式键值存储实现。服务器存储持有数据,而客户端存储可以通过TCP连接到服务器存储并执行诸如
set()插入键值对,get()检索键值对等操作。应该始终初始化一个服务器存储,因为客户端存储将等待服务器建立连接。- Parameters:
主机名 (str) – 服务器存储应运行的主机名或IP地址。
端口 (int) – 服务器存储应监听传入请求的端口。
world_size (int, 可选) – 存储用户的总数(客户端数量 + 1 用于服务器)。默认为 None(None 表示存储用户数量不固定)。
is_master (bool, 可选) – 在初始化服务器存储时为True,在客户端存储时为False。默认值为False。
超时 (timedelta, 可选) – 存储在初始化和诸如
get()和wait()的方法中使用的超时时间。默认值为 timedelta(seconds=300)wait_for_worker (bool, optional) – 是否等待所有工作进程与服务器存储连接。这仅在 world_size 是固定值时适用。默认为 True。
- Example::
>>> import torch.distributed as dist >>> from datetime import timedelta >>> # Run on process 1 (server) >>> server_store = dist.TCPStore("127.0.0.1", 1234, 2, True, timedelta(seconds=30)) >>> # Run on process 2 (client) >>> client_store = dist.TCPStore("127.0.0.1", 1234, 2, False) >>> # Use any of the store methods from either the client or server after initialization >>> server_store.set("first_key", "first_value") >>> client_store.get("first_key")
- class torch.distributed.HashStore¶
基于底层哈希映射的线程安全存储实现。此存储可以在同一进程内使用(例如,由其他线程使用),但不能跨进程使用。
- Example::
>>> import torch.distributed as dist >>> store = dist.HashStore() >>> # store can be used from other threads >>> # Use any of the store methods after initialization >>> store.set("first_key", "first_value")
- class torch.distributed.FileStore¶
一种使用文件来存储底层键值对的存储实现。
- Example::
>>> import torch.distributed as dist >>> store1 = dist.FileStore("/tmp/filestore", 2) >>> store2 = dist.FileStore("/tmp/filestore", 2) >>> # Use any of the store methods from either the client or server after initialization >>> store1.set("first_key", "first_value") >>> store2.get("first_key")
- class torch.distributed.PrefixStore¶
围绕任何3个键值存储(
TCPStore,FileStore, 和HashStore) 添加前缀到插入存储的每个键的包装器。- Parameters:
前缀 (str) – 在插入存储之前,附加到每个键前面的前缀字符串。
存储 (torch.distributed.store) – 一个构成底层键值存储的存储对象。
- torch.distributed.Store.set(self: torch._C._distributed_c10d.Store, arg0: str, arg1: str) None¶
将键值对插入存储中,基于提供的
key和value。如果key已经在存储中存在,它将用新提供的value覆盖旧值。- Example::
>>> import torch.distributed as dist >>> from datetime import timedelta >>> store = dist.TCPStore("127.0.0.1", 0, 1, True, timedelta(seconds=30)) >>> store.set("first_key", "first_value") >>> # Should return "first_value" >>> store.get("first_key")
- torch.distributed.Store.get(self: torch._C._distributed_c10d.Store, arg0: str) bytes¶
从存储中检索与给定
key关联的值。如果key不在 存储中,函数将等待timeout,这是在初始化存储时定义的, 然后抛出异常。- Parameters:
键 (str) – 该函数将返回与此键关联的值。
- Returns:
与
key关联的值,如果key存在于存储中。
- Example::
>>> import torch.distributed as dist >>> from datetime import timedelta >>> store = dist.TCPStore("127.0.0.1", 0, 1, True, timedelta(seconds=30)) >>> store.set("first_key", "first_value") >>> # Should return "first_value" >>> store.get("first_key")
- torch.distributed.Store.add(self: torch._C._distributed_c10d.Store, arg0: str, arg1: int) int¶
对给定的
key的第一次调用会创建一个与key在存储中关联的计数器,初始化为amount。随后使用相同的key调用add会将计数器按指定的amount递增。 使用已经通过set()在存储中设置过的键调用add()将会导致异常。- Example::
>>> import torch.distributed as dist >>> from datetime import timedelta >>> # Using TCPStore as an example, other store types can also be used >>> store = dist.TCPStore("127.0.0.1", 0, 1, True, timedelta(seconds=30)) >>> store.add("first_key", 1) >>> store.add("first_key", 6) >>> # Should return 7 >>> store.get("first_key")
- torch.distributed.Store.compare_set(self: torch._C._distributed_c10d.Store, arg0: str, arg1: str, arg2: str) bytes¶
将键值对插入存储中,基于提供的
key,并在插入之前执行expected_value和desired_value之间的比较。desired_value仅在key已经存在于存储中或expected_value为空字符串时才会被设置。- Parameters:
- Example::
>>> import torch.distributed as dist >>> from datetime import timedelta >>> store = dist.TCPStore("127.0.0.1", 0, 1, True, timedelta(seconds=30)) >>> store.set("key", "first_value") >>> store.compare_set("key", "first_value", "second_value") >>> # Should return "second_value" >>> store.get("key")
- torch.distributed.Store.wait(*args, **kwargs)¶
重载函数。
等待(self: torch._C._distributed_c10d.Store, arg0: list[str]) -> None
等待
keys中的每个键被添加到存储中。如果在timeout(在存储初始化期间设置)之前并非所有键都已设置,则wait将抛出异常。- Parameters:
键 (列表) – 在存储中设置之前需要等待的键列表。
- Example::
>>> import torch.distributed as dist >>> from datetime import timedelta >>> # Using TCPStore as an example, other store types can also be used >>> store = dist.TCPStore("127.0.0.1", 0, 1, True, timedelta(seconds=30)) >>> # This will throw an exception after 30 seconds >>> store.wait(["bad_key"])
等待(self: torch._C._distributed_c10d.Store, arg0: list[str], arg1: datetime.timedelta) -> None
等待
keys中的每个键被添加到存储中,并在提供的timeout未设置这些键时抛出异常。- Parameters:
键 (列表) – 在存储中设置之前需要等待的键列表。
超时 (时间间隔) – 等待键被添加的时间,超过此时间将抛出异常。
- Example::
>>> import torch.distributed as dist >>> from datetime import timedelta >>> # Using TCPStore as an example, other store types can also be used >>> store = dist.TCPStore("127.0.0.1", 0, 1, True, timedelta(seconds=30)) >>> # This will throw an exception after 10 seconds >>> store.wait(["bad_key"], timedelta(seconds=10))
- torch.distributed.Store.num_keys(self: torch._C._distributed_c10d.Store) int¶
返回存储中设置的键的数量。请注意,这个数量通常会比通过
set()和add()添加的键的数量多一个,因为一个键用于协调所有使用存储的工作者。警告
当与
TCPStore,num_keys一起使用时,返回写入底层文件的键的数量。如果存储被销毁并用相同的文件创建另一个存储,则原始键将被保留。- Returns:
存储中键的数量。
- Example::
>>> import torch.distributed as dist >>> from datetime import timedelta >>> # Using TCPStore as an example, other store types can also be used >>> store = dist.TCPStore("127.0.0.1", 0, 1, True, timedelta(seconds=30)) >>> store.set("first_key", "first_value") >>> # This should return 2 >>> store.num_keys()
- torch.distributed.Store.delete_key(self: torch._C._distributed_c10d.Store, arg0: str) bool¶
删除与
key关联的键值对。如果成功删除则返回true,否则返回false。- Parameters:
键 (str) – 要从存储中删除的键
- Returns:
True 如果
key被删除,否则 False。
- Example::
>>> import torch.distributed as dist >>> from datetime import timedelta >>> # Using TCPStore as an example, HashStore can also be used >>> store = dist.TCPStore("127.0.0.1", 0, 1, True, timedelta(seconds=30)) >>> store.set("first_key") >>> # This should return true >>> store.delete_key("first_key") >>> # This should return false >>> store.delete_key("bad_key")
- torch.distributed.Store.set_timeout(self: torch._C._distributed_c10d.Store, arg0: datetime.timedelta) None¶
设置存储的默认超时时间。此超时时间在初始化期间以及在
wait()和get()中使用。- Parameters:
超时 (时间间隔) – 在存储中设置的超时。
- Example::
>>> import torch.distributed as dist >>> from datetime import timedelta >>> # Using TCPStore as an example, other store types can also be used >>> store = dist.TCPStore("127.0.0.1", 0, 1, True, timedelta(seconds=30)) >>> store.set_timeout(timedelta(seconds=10)) >>> # This will throw an exception after 10 seconds >>> store.wait(["bad_key"])
组¶
默认情况下,集合操作在默认组(也称为世界)上进行,并且需要所有进程进入分布式函数调用。然而,某些工作负载可以从更细粒度的通信中受益。这就是分布式组发挥作用的地方。可以使用 new_group() 函数来创建新的组,这些组可以包含所有进程的任意子集。它返回一个不透明的组句柄,该句柄可以作为 group 参数传递给所有集合操作(集合操作是用于在某些已知编程模式中交换信息的分布式函数)。
- torch.distributed.new_group(ranks=None, timeout=datetime.timedelta(seconds=1800), backend=None, pg_options=None)[source]¶
创建一个新的分布式组。
此函数要求主组中的所有进程(即分布式作业的所有组成部分)都进入此函数,即使它们不会成为该组的成员。此外,所有进程中应以相同的顺序创建组。
警告
同时使用多个进程组与
NCCL后端并发是不安全的,用户应在应用程序中执行显式同步以确保一次只使用一个进程组。这意味着来自一个进程组的集体操作应在设备上完成执行(不仅仅是排队,因为CUDA执行是异步的),然后才能将来自另一个进程组的集体操作排队。有关详细信息,请参见并发使用多个NCCL通信器。- Parameters:
超时 (timedelta, 可选) – 对进程组执行操作的超时时间。默认值等于30分钟。 这适用于
gloo后端。对于nccl,只有在环境变量NCCL_BLOCKING_WAIT或NCCL_ASYNC_ERROR_HANDLING设置为 1 时才适用。当NCCL_BLOCKING_WAIT被设置时,这是进程将阻塞并等待集合操作完成的时间长度 在抛出异常之前。当NCCL_ASYNC_ERROR_HANDLING被设置时, 这是集合操作将在之后被异步中止的时间长度,并且进程将崩溃。NCCL_BLOCKING_WAIT将向用户提供错误信息,这些错误可以被捕获和处理,但由于其阻塞特性,它会有性能开销。另一方面,NCCL_ASYNC_ERROR_HANDLING的性能开销非常小, 但在出现错误时会崩溃进程。这是由于CUDA执行是异步的,继续执行用户代码不再安全,因为失败的异步NCCL操作可能导致后续CUDA操作在损坏的数据上运行。这两个环境变量中应只设置其中一个。后端 (str 或 Backend, 可选) – 要使用的后端。根据构建时的配置,有效值为
gloo和nccl。 默认情况下使用与全局组相同的后端。此字段应以小写字符串形式给出(例如,"gloo"),也可以通过Backend属性访问(例如,Backend.GLOO)。如果传递了None,则将使用默认进程组对应的后端。默认值为None。pg_options (ProcessGroupOptions, 可选) – 进程组选项 指定在构建特定进程组时需要传递的其他选项。例如,对于
nccl后端,可以指定is_high_priority_stream,以便 进程组可以选择高优先级的cuda流。
- Returns:
可用于集体调用的分布式组的句柄。
- torch.distributed.get_group_rank(group, global_rank)[source]¶
将全局排名转换为组内排名。
global_rank必须是group的一部分,否则将引发 RuntimeError。- Parameters:
组 (进程组) – 用于查找相对排名的进程组。
全局排名 (int) – 要查询的全局排名。
- Returns:
相对于
group的global_rank的组排名- Return type:
注意:在默认进程组上调用此函数将返回身份标识
点对点通信¶
isend() 和 irecv()
在使用时返回分布式请求对象。一般来说,这种对象的类型是未指定的
因为它们不应该手动创建,但可以保证支持两种方法:
is_completed()- 如果操作已完成,则返回Truewait()- 将阻塞进程,直到操作完成。is_completed()保证一旦返回则返回True。
- torch.distributed.isend(tensor, dst, group=None, tag=0)[source]¶
异步发送一个张量。
警告
在请求完成之前修改
tensor会导致未定义的行为。
- torch.distributed.batch_isend_irecv(p2p_op_list)[source]¶
异步发送或接收一批张量并返回请求列表。
处理
p2p_op_list中的每个操作,并返回相应的请求。目前支持NCCL、Gloo和UCC后端。- Parameters:
p2p_op_list – 一个点对点操作的列表(每个操作符的类型为
torch.distributed.P2POp)。列表中isend/irecv的顺序很重要,需要与远程端对应的isend/irecv匹配。- Returns:
调用 op_list 中相应操作返回的分布式请求对象列表。
示例
>>> send_tensor = torch.arange(2) + 2 * rank >>> recv_tensor = torch.randn(2) >>> send_op = dist.P2POp(dist.isend, send_tensor, (rank + 1)%world_size) >>> recv_op = dist.P2POp(dist.irecv, recv_tensor, (rank - 1 + world_size)%world_size) >>> reqs = batch_isend_irecv([send_op, recv_op]) >>> for req in reqs: >>> req.wait() >>> recv_tensor tensor([2, 3]) # Rank 0 tensor([0, 1]) # Rank 1
注意
注意,当此API与NCCL PG后端一起使用时,用户必须将当前GPU设备设置为torch.cuda.set_device,否则会导致意外挂起问题。
此外,如果此API是
group中的第一个集体调用,并且传递给dist.P2POp,则group的所有秩都必须参与此API调用;否则,行为是未定义的。如果此API调用不是group中的第一个集体调用,则允许仅涉及group的一组秩的批量P2P操作。
同步和异步集体操作¶
每个集体操作函数支持以下两种操作,具体取决于传递给集体的async_op标志的设置:
同步操作 - 默认模式,当 async_op 被设置为 False 时。
当函数返回时,保证集体操作已经执行。对于 CUDA 操作,不保证 CUDA 操作已完成,因为 CUDA 操作是异步的。对于 CPU 集体操作,任何使用集体调用输出的进一步函数调用将按预期行为运行。对于 CUDA 集体操作,在同一 CUDA 流上使用输出的函数调用将按预期行为运行。用户必须注意在不同流下运行时的同步问题。有关 CUDA 语义(如流同步)的详细信息,请参阅 CUDA 语义。
请参阅以下脚本,以查看 CPU 和 CUDA 操作中这些语义的差异示例。
异步操作 - 当 async_op 设置为 True 时。集体操作函数返回一个分布式请求对象。通常情况下,你不需要手动创建它,并且保证支持两种方法:
is_completed()- 在CPU集合操作的情况下,如果已完成则返回True。在CUDA操作的情况下, 如果操作已成功排队到CUDA流,并且可以在默认流上使用输出而无需进一步同步,则返回True。wait()- 在CPU集合操作的情况下,将阻塞进程直到操作完成。在CUDA集合操作的情况下,将阻塞直到操作成功地排队到CUDA流上,并且可以在默认流上使用输出而无需进一步同步。get_future()- 返回torch._C.Future对象。支持NCCL,也支持GLOO和MPI上的大多数操作,除了点对点操作。 注意:随着我们继续采用Futures并合并API,get_future()调用可能会变得冗余。
示例
以下代码可以作为使用分布式集合操作时CUDA操作语义的参考。 它显示了在不同CUDA流上使用集合输出时显式同步的必要性:
# Code runs on each rank.
dist.init_process_group("nccl", rank=rank, world_size=2)
output = torch.tensor([rank]).cuda(rank)
s = torch.cuda.Stream()
handle = dist.all_reduce(output, async_op=True)
# Wait ensures the operation is enqueued, but not necessarily complete.
handle.wait()
# Using result on non-default stream.
with torch.cuda.stream(s):
s.wait_stream(torch.cuda.default_stream())
output.add_(100)
if rank == 0:
# if the explicit call to wait_stream was omitted, the output below will be
# non-deterministically 1 or 101, depending on whether the allreduce overwrote
# the value after the add completed.
print(output)
集体函数¶
- torch.distributed.broadcast(tensor, src, group=None, async_op=False)[source]¶
将张量广播到整个组。
tensor必须在所有参与集体操作的进程中具有相同数量的元素。
- torch.distributed.broadcast_object_list(object_list, src=0, group=None, device=None)[source]¶
Broadcasts picklable objects in
object_listto the whole group. Similar tobroadcast(), but Python objects can be passed in. Note that all objects inobject_listmust be picklable in order to be broadcasted。- Parameters:
object_list (List[Any]) – 要广播的输入对象列表。 每个对象都必须是可pickle的。只有
src秩上的对象会被广播,但每个秩都必须提供相同大小的列表。src (int) – 要从中广播
object_list的源等级。组 – (进程组,可选):要操作的进程组。如果为None,则将使用默认进程组。默认值是
None。设备 (
torch.device, 可选) – 如果不是None,对象将被序列化并转换为张量,然后在广播之前移动到device。默认值是None。
- Returns:
None. 如果秩是组的一部分,object_list将包含从src秩广播的对象。
注意
对于基于NCCL的进程组,对象的内部张量表示必须在通信之前移动到GPU设备。在这种情况下,使用的设备由
torch.cuda.current_device()给出,并且用户有责任确保设置为每个秩都有一个单独的GPU,通过torch.cuda.set_device()。注意
请注意,此API与
all_gather()集体略有不同,因为它不提供async_op句柄,因此 将是一个阻塞调用。警告
broadcast_object_list()隐式使用了pickle模块,这已知是不安全的。可以构造恶意的pickle数据,在反序列化过程中执行任意代码。仅在信任数据时调用此函数。- Example::
>>> # Note: Process group initialization omitted on each rank. >>> import torch.distributed as dist >>> if dist.get_rank() == 0: >>> # Assumes world_size of 3. >>> objects = ["foo", 12, {1: 2}] # any picklable object >>> else: >>> objects = [None, None, None] >>> # Assumes backend is not NCCL >>> device = torch.device("cpu") >>> dist.broadcast_object_list(objects, src=0, device=device) >>> objects ['foo', 12, {1: 2}]
- torch.distributed.all_reduce(tensor, op=<RedOpType.SUM: 0>, group=None, async_op=False)[source]¶
在所有机器之间减少张量数据,使得所有机器都得到最终结果。
调用后
tensor在所有进程中将逐位完全相同。支持复数张量。
- Parameters:
- Returns:
异步工作句柄,如果 async_op 设置为 True。 如果没有设置 async_op 或者不属于该组,则为 None。
示例
>>> # All tensors below are of torch.int64 type. >>> # We have 2 process groups, 2 ranks. >>> tensor = torch.arange(2, dtype=torch.int64) + 1 + 2 * rank >>> tensor tensor([1, 2]) # Rank 0 tensor([3, 4]) # Rank 1 >>> dist.all_reduce(tensor, op=ReduceOp.SUM) >>> tensor tensor([4, 6]) # Rank 0 tensor([4, 6]) # Rank 1
>>> # All tensors below are of torch.cfloat type. >>> # We have 2 process groups, 2 ranks. >>> tensor = torch.tensor([1+1j, 2+2j], dtype=torch.cfloat) + 2 * rank * (1+1j) >>> tensor tensor([1.+1.j, 2.+2.j]) # Rank 0 tensor([3.+3.j, 4.+4.j]) # Rank 1 >>> dist.all_reduce(tensor, op=ReduceOp.SUM) >>> tensor tensor([4.+4.j, 6.+6.j]) # Rank 0 tensor([4.+4.j, 6.+6.j]) # Rank 1
- torch.distributed.reduce(tensor, dst, op=<RedOpType.SUM: 0>, group=None, async_op=False)[source]¶
在所有机器上减少张量数据。
只有排名为
dst的进程将接收最终结果。
- torch.distributed.all_gather(tensor_list, tensor, group=None, async_op=False)[source]¶
从整个组中收集张量并放入列表中。
支持复数张量。
- Parameters:
- Returns:
异步工作句柄,如果 async_op 设置为 True。 如果没有设置 async_op 或者不属于该组,则为 None。
示例
>>> # All tensors below are of torch.int64 dtype. >>> # We have 2 process groups, 2 ranks. >>> tensor_list = [torch.zeros(2, dtype=torch.int64) for _ in range(2)] >>> tensor_list [tensor([0, 0]), tensor([0, 0])] # Rank 0 and 1 >>> tensor = torch.arange(2, dtype=torch.int64) + 1 + 2 * rank >>> tensor tensor([1, 2]) # Rank 0 tensor([3, 4]) # Rank 1 >>> dist.all_gather(tensor_list, tensor) >>> tensor_list [tensor([1, 2]), tensor([3, 4])] # Rank 0 [tensor([1, 2]), tensor([3, 4])] # Rank 1
>>> # All tensors below are of torch.cfloat dtype. >>> # We have 2 process groups, 2 ranks. >>> tensor_list = [torch.zeros(2, dtype=torch.cfloat) for _ in range(2)] >>> tensor_list [tensor([0.+0.j, 0.+0.j]), tensor([0.+0.j, 0.+0.j])] # Rank 0 and 1 >>> tensor = torch.tensor([1+1j, 2+2j], dtype=torch.cfloat) + 2 * rank * (1+1j) >>> tensor tensor([1.+1.j, 2.+2.j]) # Rank 0 tensor([3.+3.j, 4.+4.j]) # Rank 1 >>> dist.all_gather(tensor_list, tensor) >>> tensor_list [tensor([1.+1.j, 2.+2.j]), tensor([3.+3.j, 4.+4.j])] # Rank 0 [tensor([1.+1.j, 2.+2.j]), tensor([3.+3.j, 4.+4.j])] # Rank 1
- torch.distributed.all_gather_into_tensor(output_tensor, input_tensor, group=None, async_op=False)[source]¶
从所有秩收集张量并将其放入一个单一的输出张量中。
- Parameters:
output_tensor (Tensor) – 用于容纳所有秩的张量元素的输出张量。它必须正确地调整大小以具有以下形式之一: (i) 沿主维度连接所有输入张量;关于“连接”的定义,请参见
torch.cat(); (ii) 沿主维度堆叠所有输入张量;关于“堆叠”的定义,请参见torch.stack()。 下面的示例可能更好地解释支持的输出形式。input_tensor (Tensor) – 从当前秩收集的张量。 与
all_gatherAPI 不同,此 API 中的输入张量在所有秩上必须具有相同的大小。组 (进程组, 可选) – 要操作的进程组。如果为None, 将使用默认的进程组。
async_op (bool, optional) – 此操作是否应为异步操作
- Returns:
异步工作句柄,如果 async_op 设置为 True。 如果没有设置 async_op 或者不属于该组,则为 None。
示例
>>> # All tensors below are of torch.int64 dtype and on CUDA devices. >>> # We have two ranks. >>> device = torch.device(f'cuda:{rank}') >>> tensor_in = torch.arange(2, dtype=torch.int64, device=device) + 1 + 2 * rank >>> tensor_in tensor([1, 2], device='cuda:0') # Rank 0 tensor([3, 4], device='cuda:1') # Rank 1 >>> # Output in concatenation form >>> tensor_out = torch.zeros(world_size * 2, dtype=torch.int64, device=device) >>> dist.all_gather_into_tensor(tensor_out, tensor_in) >>> tensor_out tensor([1, 2, 3, 4], device='cuda:0') # Rank 0 tensor([1, 2, 3, 4], device='cuda:1') # Rank 1 >>> # Output in stack form >>> tensor_out2 = torch.zeros(world_size, 2, dtype=torch.int64, device=device) >>> dist.all_gather_into_tensor(tensor_out2, tensor_in) >>> tensor_out2 tensor([[1, 2], [3, 4]], device='cuda:0') # Rank 0 tensor([[1, 2], [3, 4]], device='cuda:1') # Rank 1
警告
Gloo 后端不支持此 API。
- torch.distributed.all_gather_object(object_list, obj, group=None)[source]¶
将整个组中的可序列化对象收集到一个列表中。类似于
all_gather(),但可以传入Python对象。请注意,对象必须是可序列化的才能被收集。- Parameters:
对象列表 (列表[任意]) – 输出列表。它的大小应与该组的大小相匹配,并且将包含输出。
对象 (任意类型) – 从当前进程广播的可序列化的Python对象。
组 (进程组, 可选) – 要操作的进程组。如果为 None, 将使用默认的进程组。默认值是
None。
- Returns:
无。如果调用的秩是该组的一部分,则集体操作的结果将填充到输入
object_list中。如果调用的秩不是该组的一部分,则传递的object_list将保持不变。
注意
请注意,此API与
all_gather()集体略有不同,因为它不提供async_op句柄,因此 将是一个阻塞调用。注意
对于基于NCCL的进程组,对象的内部张量表示必须在通信之前移动到GPU设备。在这种情况下,使用的设备由
torch.cuda.current_device()给出,并且用户有责任确保设置为每个秩都有一个独立的GPU,通过torch.cuda.set_device()。警告
all_gather_object()隐式使用了pickle模块,这被认为是不安全的。可以构造恶意的pickle数据,在反序列化过程中执行任意代码。仅在信任数据时调用此函数。- Example::
>>> # Note: Process group initialization omitted on each rank. >>> import torch.distributed as dist >>> # Assumes world_size of 3. >>> gather_objects = ["foo", 12, {1: 2}] # any picklable object >>> output = [None for _ in gather_objects] >>> dist.all_gather_object(output, gather_objects[dist.get_rank()]) >>> output ['foo', 12, {1: 2}]
- torch.distributed.gather(tensor, gather_list=None, dst=0, group=None, async_op=False)[source]¶
在单个进程中收集一组张量。
- torch.distributed.gather_object(obj, object_gather_list=None, dst=0, group=None)[source]¶
从整个组中在一个进程中收集可序列化的对象。 类似于
gather(),但可以传入Python对象。请注意,对象必须是可序列化的才能被收集。- Parameters:
- Returns:
无。在
dst排名中,object_gather_list将包含集体操作的输出。
注意
请注意,此API与gather集体操作略有不同 因为它不提供异步操作句柄,因此将是一个阻塞调用。
注意
对于基于NCCL的进程组,对象的内部张量表示必须在通信之前移动到GPU设备。在这种情况下,使用的设备由
torch.cuda.current_device()给出,并且用户有责任确保设置为每个秩都有一个独立的GPU,通过torch.cuda.set_device()。警告
gather_object()隐式使用了pickle模块,这被认为是不安全的。可以构造恶意的pickle数据,在反序列化过程中执行任意代码。仅在信任数据时调用此函数。- Example::
>>> # Note: Process group initialization omitted on each rank. >>> import torch.distributed as dist >>> # Assumes world_size of 3. >>> gather_objects = ["foo", 12, {1: 2}] # any picklable object >>> output = [None for _ in gather_objects] >>> dist.gather_object( ... gather_objects[dist.get_rank()], ... output if dist.get_rank() == 0 else None, ... dst=0 ... ) >>> # On rank 0 >>> output ['foo', 12, {1: 2}]
- torch.distributed.scatter(tensor, scatter_list=None, src=0, group=None, async_op=False)[source]¶
将一个张量列表分散到组中的所有进程。
每个进程将接收一个张量,并将其数据存储在
tensor参数中。支持复数张量。
- Parameters:
- Returns:
异步工作句柄,如果 async_op 设置为 True。 如果没有设置 async_op 或者不属于该组,则为 None。
注意
请注意,scatter_list 中的所有 Tensor 必须具有相同的大小。
- Example::
>>> # Note: Process group initialization omitted on each rank. >>> import torch.distributed as dist >>> tensor_size = 2 >>> t_ones = torch.ones(tensor_size) >>> t_fives = torch.ones(tensor_size) * 5 >>> output_tensor = torch.zeros(tensor_size) >>> if dist.get_rank() == 0: >>> # Assumes world_size of 2. >>> # Only tensors, all of which must be the same size. >>> scatter_list = [t_ones, t_fives] >>> else: >>> scatter_list = None >>> dist.scatter(output_tensor, scatter_list, src=0) >>> # Rank i gets scatter_list[i]. For example, on rank 1: >>> output_tensor tensor([5., 5.])
- torch.distributed.scatter_object_list(scatter_object_output_list, scatter_object_input_list, src=0, group=None)[source]¶
将可序列化对象分散到整个组中的
scatter_object_input_list。类似于scatter(),但可以传入 Python 对象。在每个 rank 上,分散的对象将被存储为scatter_object_output_list的第一个元素。请注意,scatter_object_input_list中的所有对象都必须是可序列化的,以便进行分散。- Parameters:
scatter_object_output_list (List[Any]) – 非空列表,其第一个元素将存储散列到此秩的对象。
scatter_object_input_list (List[Any]) – 需要分发的输入对象列表。 每个对象都必须是可pickle的。只有在
src等级上的对象才会被分发,对于非源等级,该参数可以是None。src (int) – 要从中分散的源秩
scatter_object_input_list。组 – (进程组,可选):要操作的进程组。如果为None,则将使用默认进程组。默认值是
None。
- Returns:
None. 如果秩是组的一部分,scatter_object_output_list将把其第一个元素设置为该秩的分散对象。
注意
请注意,此API与scatter集体略有不同 因为它不提供一个
async_op句柄,因此将是一个 阻塞调用。警告
scatter_object_list()隐式使用了pickle模块,这已知是不安全的。可以构造恶意的pickle数据,在反序列化过程中执行任意代码。仅在信任数据时调用此函数。- Example::
>>> # Note: Process group initialization omitted on each rank. >>> import torch.distributed as dist >>> if dist.get_rank() == 0: >>> # Assumes world_size of 3. >>> objects = ["foo", 12, {1: 2}] # any picklable object >>> else: >>> # Can be any list on non-src ranks, elements are not used. >>> objects = [None, None, None] >>> output_list = [None] >>> dist.scatter_object_list(output_list, objects, src=0) >>> # Rank i gets objects[i]. For example, on rank 2: >>> output_list [{1: 2}]
- torch.distributed.reduce_scatter(output, input_list, op=<RedOpType.SUM: 0>, group=None, async_op=False)[source]¶
减少,然后将一组张量列表分散到所有进程中。
- torch.distributed.reduce_scatter_tensor(output, input, op=<RedOpType.SUM: 0>, group=None, async_op=False)[source]¶
减少,然后将张量分散到组中的所有秩。
- Parameters:
- Returns:
异步工作句柄,如果 async_op 设置为 True。 如果没有设置 async_op 或者不属于该组,则为 None。
示例
>>> # All tensors below are of torch.int64 dtype and on CUDA devices. >>> # We have two ranks. >>> device = torch.device(f'cuda:{rank}') >>> tensor_out = torch.zeros(2, dtype=torch.int64, device=device) >>> # Input in concatenation form >>> tensor_in = torch.arange(world_size * 2, dtype=torch.int64, device=device) >>> tensor_in tensor([0, 1, 2, 3], device='cuda:0') # Rank 0 tensor([0, 1, 2, 3], device='cuda:1') # Rank 1 >>> dist.reduce_scatter_tensor(tensor_out, tensor_in) >>> tensor_out tensor([0, 2], device='cuda:0') # Rank 0 tensor([4, 6], device='cuda:1') # Rank 1 >>> # Input in stack form >>> tensor_in = torch.reshape(tensor_in, (world_size, 2)) >>> tensor_in tensor([[0, 1], [2, 3]], device='cuda:0') # Rank 0 tensor([[0, 1], [2, 3]], device='cuda:1') # Rank 1 >>> dist.reduce_scatter_tensor(tensor_out, tensor_in) >>> tensor_out tensor([0, 2], device='cuda:0') # Rank 0 tensor([4, 6], device='cuda:1') # Rank 1
警告
Gloo 后端不支持此 API。
- torch.distributed.all_to_all_single(output, input, output_split_sizes=None, input_split_sizes=None, group=None, async_op=False)[source]¶
每个进程将输入张量拆分,然后将拆分后的列表散播到组内的所有进程中。接着,将从组内所有进程中接收到的张量进行拼接,并返回一个输出张量。
支持复数张量。
- Parameters:
输出 (张量) – 汇聚连接的输出张量。
输入 (张量) – 用于散射的输入张量。
output_split_sizes – (list[Int], 可选): 输出分割大小,用于维度 0 如果指定为 None 或空,则
output张量的维度 0 必须能被world_size整除。input_split_sizes – (list[Int], 可选): 输入分割大小,用于维度 0 如果指定为 None 或空,则
input张量的维度 0 必须能被world_size整除。组 (进程组, 可选) – 要操作的进程组。如果为None, 将使用默认的进程组。
async_op (bool, optional) – 此操作是否应为异步操作。
- Returns:
异步工作句柄,如果 async_op 设置为 True。 如果没有设置 async_op 或者不属于该组,则为 None。
警告
all_to_all_single 是实验性的,可能会发生变化。
示例
>>> input = torch.arange(4) + rank * 4 >>> input tensor([0, 1, 2, 3]) # Rank 0 tensor([4, 5, 6, 7]) # Rank 1 tensor([8, 9, 10, 11]) # Rank 2 tensor([12, 13, 14, 15]) # Rank 3 >>> output = torch.empty([4], dtype=torch.int64) >>> dist.all_to_all_single(output, input) >>> output tensor([0, 4, 8, 12]) # Rank 0 tensor([1, 5, 9, 13]) # Rank 1 tensor([2, 6, 10, 14]) # Rank 2 tensor([3, 7, 11, 15]) # Rank 3
>>> # Essentially, it is similar to following operation: >>> scatter_list = list(input.chunk(world_size)) >>> gather_list = list(output.chunk(world_size)) >>> for i in range(world_size): >>> dist.scatter(gather_list[i], scatter_list if i == rank else [], src = i)
>>> # Another example with uneven split >>> input tensor([0, 1, 2, 3, 4, 5]) # Rank 0 tensor([10, 11, 12, 13, 14, 15, 16, 17, 18]) # Rank 1 tensor([20, 21, 22, 23, 24]) # Rank 2 tensor([30, 31, 32, 33, 34, 35, 36]) # Rank 3 >>> input_splits [2, 2, 1, 1] # Rank 0 [3, 2, 2, 2] # Rank 1 [2, 1, 1, 1] # Rank 2 [2, 2, 2, 1] # Rank 3 >>> output_splits [2, 3, 2, 2] # Rank 0 [2, 2, 1, 2] # Rank 1 [1, 2, 1, 2] # Rank 2 [1, 2, 1, 1] # Rank 3 >>> output = ... >>> dist.all_to_all_single(output, input, output_splits, input_splits) >>> output tensor([ 0, 1, 10, 11, 12, 20, 21, 30, 31]) # Rank 0 tensor([ 2, 3, 13, 14, 22, 32, 33]) # Rank 1 tensor([ 4, 15, 16, 23, 34, 35]) # Rank 2 tensor([ 5, 17, 18, 24, 36]) # Rank 3
>>> # Another example with tensors of torch.cfloat type. >>> input = torch.tensor([1+1j, 2+2j, 3+3j, 4+4j], dtype=torch.cfloat) + 4 * rank * (1+1j) >>> input tensor([1+1j, 2+2j, 3+3j, 4+4j]) # Rank 0 tensor([5+5j, 6+6j, 7+7j, 8+8j]) # Rank 1 tensor([9+9j, 10+10j, 11+11j, 12+12j]) # Rank 2 tensor([13+13j, 14+14j, 15+15j, 16+16j]) # Rank 3 >>> output = torch.empty([4], dtype=torch.int64) >>> dist.all_to_all_single(output, input) >>> output tensor([1+1j, 5+5j, 9+9j, 13+13j]) # Rank 0 tensor([2+2j, 6+6j, 10+10j, 14+14j]) # Rank 1 tensor([3+3j, 7+7j, 11+11j, 15+15j]) # Rank 2 tensor([4+4j, 8+8j, 12+12j, 16+16j]) # Rank 3
- torch.distributed.all_to_all(output_tensor_list, input_tensor_list, group=None, async_op=False)[source]¶
每个进程将输入张量列表分散到组内的所有进程中,并在输出列表中返回收集到的张量列表。
支持复数张量。
- Parameters:
- Returns:
异步工作句柄,如果 async_op 设置为 True。 如果没有设置 async_op 或者不属于该组,则为 None。
警告
all_to_all 是实验性的,可能会发生变化。
示例
>>> input = torch.arange(4) + rank * 4 >>> input = list(input.chunk(4)) >>> input [tensor([0]), tensor([1]), tensor([2]), tensor([3])] # Rank 0 [tensor([4]), tensor([5]), tensor([6]), tensor([7])] # Rank 1 [tensor([8]), tensor([9]), tensor([10]), tensor([11])] # Rank 2 [tensor([12]), tensor([13]), tensor([14]), tensor([15])] # Rank 3 >>> output = list(torch.empty([4], dtype=torch.int64).chunk(4)) >>> dist.all_to_all(output, input) >>> output [tensor([0]), tensor([4]), tensor([8]), tensor([12])] # Rank 0 [tensor([1]), tensor([5]), tensor([9]), tensor([13])] # Rank 1 [tensor([2]), tensor([6]), tensor([10]), tensor([14])] # Rank 2 [tensor([3]), tensor([7]), tensor([11]), tensor([15])] # Rank 3
>>> # Essentially, it is similar to following operation: >>> scatter_list = input >>> gather_list = output >>> for i in range(world_size): >>> dist.scatter(gather_list[i], scatter_list if i == rank else [], src=i)
>>> input tensor([0, 1, 2, 3, 4, 5]) # Rank 0 tensor([10, 11, 12, 13, 14, 15, 16, 17, 18]) # Rank 1 tensor([20, 21, 22, 23, 24]) # Rank 2 tensor([30, 31, 32, 33, 34, 35, 36]) # Rank 3 >>> input_splits [2, 2, 1, 1] # Rank 0 [3, 2, 2, 2] # Rank 1 [2, 1, 1, 1] # Rank 2 [2, 2, 2, 1] # Rank 3 >>> output_splits [2, 3, 2, 2] # Rank 0 [2, 2, 1, 2] # Rank 1 [1, 2, 1, 2] # Rank 2 [1, 2, 1, 1] # Rank 3 >>> input = list(input.split(input_splits)) >>> input [tensor([0, 1]), tensor([2, 3]), tensor([4]), tensor([5])] # Rank 0 [tensor([10, 11, 12]), tensor([13, 14]), tensor([15, 16]), tensor([17, 18])] # Rank 1 [tensor([20, 21]), tensor([22]), tensor([23]), tensor([24])] # Rank 2 [tensor([30, 31]), tensor([32, 33]), tensor([34, 35]), tensor([36])] # Rank 3 >>> output = ... >>> dist.all_to_all(output, input) >>> output [tensor([0, 1]), tensor([10, 11, 12]), tensor([20, 21]), tensor([30, 31])] # Rank 0 [tensor([2, 3]), tensor([13, 14]), tensor([22]), tensor([32, 33])] # Rank 1 [tensor([4]), tensor([15, 16]), tensor([23]), tensor([34, 35])] # Rank 2 [tensor([5]), tensor([17, 18]), tensor([24]), tensor([36])] # Rank 3
>>> # Another example with tensors of torch.cfloat type. >>> input = torch.tensor([1+1j, 2+2j, 3+3j, 4+4j], dtype=torch.cfloat) + 4 * rank * (1+1j) >>> input = list(input.chunk(4)) >>> input [tensor([1+1j]), tensor([2+2j]), tensor([3+3j]), tensor([4+4j])] # Rank 0 [tensor([5+5j]), tensor([6+6j]), tensor([7+7j]), tensor([8+8j])] # Rank 1 [tensor([9+9j]), tensor([10+10j]), tensor([11+11j]), tensor([12+12j])] # Rank 2 [tensor([13+13j]), tensor([14+14j]), tensor([15+15j]), tensor([16+16j])] # Rank 3 >>> output = list(torch.empty([4], dtype=torch.int64).chunk(4)) >>> dist.all_to_all(output, input) >>> output [tensor([1+1j]), tensor([5+5j]), tensor([9+9j]), tensor([13+13j])] # Rank 0 [tensor([2+2j]), tensor([6+6j]), tensor([10+10j]), tensor([14+14j])] # Rank 1 [tensor([3+3j]), tensor([7+7j]), tensor([11+11j]), tensor([15+15j])] # Rank 2 [tensor([4+4j]), tensor([8+8j]), tensor([12+12j]), tensor([16+16j])] # Rank 3
- torch.distributed.barrier(group=None, async_op=False, device_ids=None)[source]¶
同步所有进程。
这个集体块会一直处理,直到整个组进入此函数, 如果 async_op 为 False,或者异步工作句柄在调用 wait() 时。
- torch.distributed.monitored_barrier(group=None, timeout=None, wait_all_ranks=False)[source]¶
与
torch.distributed.barrier类似,同步所有进程,但采用可配置的超时时间,并能够报告在该超时时间内未通过此屏障的进程编号。具体来说,对于非零编号的进程,将阻塞直到从编号为 0 的进程接收到发送/接收数据。编号为 0 的进程将阻塞直到处理完其他所有进程的发送/接收操作,并会报告未能及时响应的进程的失败情况。请注意,如果有一个进程未能到达 monitored_barrier(例如由于死锁),则所有其他进程都会在 monitored_barrier 处失败。这个集体操作将阻塞组中的所有进程/秩,直到整个组成功退出函数,这使得它在调试和同步时非常有用。然而,它可能会对性能产生影响,因此只应在需要主机端完全同步点的调试或场景中使用。为了调试目的,可以在应用程序的集体调用之前插入此屏障,以检查是否有任何秩处于不同步状态。
注意
请注意,此集体操作仅支持GLOO后端。
- Parameters:
组 (进程组, 可选) – 要操作的进程组。如果为
None,将使用默认的进程组。超时 (datetime.timedelta, 可选) – 监控屏障的超时时间。 如果为
None,将使用默认进程组超时时间。wait_all_ranks (布尔值, 可选) – 是否收集所有失败的等级。默认情况下,此值为
False和monitored_barrier,在等级 0 上遇到第一个失败的等级时会快速失败并抛出错误。通过设置wait_all_ranks=Truemonitored_barrier将收集所有失败的等级,并抛出包含所有失败等级信息的错误。
- Returns:
None.
- Example::
>>> # Note: Process group initialization omitted on each rank. >>> import torch.distributed as dist >>> if dist.get_rank() != 1: >>> dist.monitored_barrier() # Raises exception indicating that >>> # rank 1 did not call into monitored_barrier. >>> # Example with wait_all_ranks=True >>> if dist.get_rank() == 0: >>> dist.monitored_barrier(wait_all_ranks=True) # Raises exception >>> # indicating that ranks 1, 2, ... world_size - 1 did not call into >>> # monitored_barrier.
- class torch.distributed.ReduceOp¶
一个类似枚举的类,用于可用的减少操作:
SUM,PRODUCT,MIN,MAX,BAND,BOR,BXOR, 和PREMUL_SUM。BAND,BOR, 和BXOR约简在使用NCCL后端时不可用。AVG将值除以世界大小,然后再在各个秩之间求和。AVG仅在使用NCCL后端时可用, 并且仅适用于 NCCL 版本 2.10 或更高版本。PREMUL_SUM在本地将输入乘以给定的标量,然后再进行归约。PREMUL_SUM仅在NCCL后端可用, 并且仅在 NCCL 版本 2.11 或更高版本中可用。用户应使用torch.distributed._make_nccl_premul_sum。此外,
MAX、MIN和PRODUCT不支持复数张量。该类的值可以作为属性访问,例如,
ReduceOp.SUM。 它们用于指定归约集合的策略,例如,reduce(),all_reduce_multigpu()等。该类不支持
__members__属性。
集体通信性能分析¶
请注意,您可以使用 torch.profiler(推荐,仅在 1.8.1 版本后可用)或 torch.autograd.profiler 来分析此处提到的集体通信和点对点通信 API。所有开箱即用的后端(gloo, nccl, mpi)都受支持,并且集体通信的使用将在分析输出/跟踪中如预期那样呈现。分析您的代码与任何常规的 torch 操作符相同:
import torch
import torch.distributed as dist
with torch.profiler():
tensor = torch.randn(20, 10)
dist.all_reduce(tensor)
请参阅分析器文档以获取分析器功能的完整概述。
多GPU集体函数¶
警告
多GPU功能将被弃用。如果您必须使用它们,请稍后查阅我们的文档。
如果你在每个节点上拥有多个GPU,当使用NCCL和Gloo后端时,
broadcast_multigpu()
all_reduce_multigpu()
reduce_multigpu()
all_gather_multigpu() 和
reduce_scatter_multigpu() 支持在每个节点内的多个GPU之间进行分布式集合操作。这些功能可以潜在地提高整体的分布式训练性能,并且可以通过传递张量列表轻松使用。传递的张量列表中的每个张量都必须位于调用该函数的主机上的不同GPU设备上。请注意,所有分布式进程中的张量列表长度必须相同。同时请注意,目前多GPU集合函数仅支持NCCL后端。
例如,如果我们用于分布式训练的系统有 2 个节点,每个节点有 8 个 GPU。在 16 个 GPU 中的每一个上,都有一个张量需要进行 all-reduce 操作。以下代码可以作为参考:
在节点 0 上运行的代码
import torch
import torch.distributed as dist
dist.init_process_group(backend="nccl",
init_method="file:///distributed_test",
world_size=2,
rank=0)
tensor_list = []
for dev_idx in range(torch.cuda.device_count()):
tensor_list.append(torch.FloatTensor([1]).cuda(dev_idx))
dist.all_reduce_multigpu(tensor_list)
在节点 1 上运行的代码
import torch
import torch.distributed as dist
dist.init_process_group(backend="nccl",
init_method="file:///distributed_test",
world_size=2,
rank=1)
tensor_list = []
for dev_idx in range(torch.cuda.device_count()):
tensor_list.append(torch.FloatTensor([1]).cuda(dev_idx))
dist.all_reduce_multigpu(tensor_list)
调用之后,两个节点上的所有16个张量都将具有经过全部约简后的值16
- torch.distributed.broadcast_multigpu(tensor_list, src, group=None, async_op=False, src_tensor=0)[source]¶
将张量广播到整个组,每个节点上有多个GPU张量。
tensor必须在所有参与集体操作的进程的GPU上具有相同数量的元素。列表中的每个张量必须位于不同的GPU上目前仅支持 nccl 和 gloo 后端 张量应仅为 GPU 张量
- Parameters:
tensor_list (List[Tensor]) – 参与集体操作的张量。如果
src是秩,那么src_tensor的指定tensor_list(tensor_list[src_tensor]) 元素将 广播到 src 进程中的所有其他张量(在不同 GPU 上),以及所有其他非 src 进程中的tensor_list张量。 你还需要确保len(tensor_list)对于调用此函数的所有分布式进程是相同的。src (int) – 源张量的秩(维度数)。
组 (进程组, 可选) – 要操作的进程组。如果为None, 将使用默认的进程组。
async_op (bool, optional) – 此操作是否应为异步操作
src_tensor (int, 可选) – 源张量在
tensor_list内的秩
- Returns:
异步工作句柄,如果 async_op 设置为 True。 如果没有设置 async_op 或者不属于该组,则为 None。
- torch.distributed.all_reduce_multigpu(tensor_list, op=<RedOpType.SUM: 0>, group=None, async_op=False)[source]¶
在所有机器之间减少张量数据,使得所有机器都能得到最终结果。此函数在每个节点上减少多个张量,而每个张量位于不同的 GPU 上。 因此,张量列表中的输入张量需要是 GPU 张量。 此外,张量列表中的每个张量都需要位于不同的 GPU 上。
调用之后,所有
tensor在tensor_list中都会在所有进程中按位完全相同。支持复数张量。
目前仅支持 nccl 和 gloo 后端 张量应仅为 GPU 张量
- Parameters:
- Returns:
异步工作句柄,如果 async_op 设置为 True。 如果没有设置 async_op 或者不属于该组,则为 None。
- torch.distributed.reduce_multigpu(tensor_list, dst, op=<RedOpType.SUM: 0>, group=None, async_op=False, dst_tensor=0)[source]¶
在所有机器的多个GPU上减少张量数据。
tensor_list中的每个张量 应位于不同的GPU上仅进程编号为
tensor_list[dst_tensor]的 GPU 上的进程dst将接收最终结果。目前仅支持 nccl 后端 张量应仅为 GPU 张量
- Parameters:
tensor_list (List[Tensor]) – 集合通信的输入和输出GPU张量。该函数会原地操作。 你还需要确保调用此函数的所有分布式进程中的
len(tensor_list)是相同的。dst (int) – 目标等级
操作 (可选) – 以下值之一
torch.distributed.ReduceOp枚举。指定用于元素级归约的操作。组 (进程组, 可选) – 要操作的进程组。如果为None, 将使用默认的进程组。
async_op (bool, optional) – 此操作是否应为异步操作
dst_tensor (int, 可选) – 目标张量的秩在
tensor_list
- Returns:
异步工作处理,如果 async_op 设置为 True。 否则为 None。
- torch.distributed.all_gather_multigpu(output_tensor_lists, input_tensor_list, group=None, async_op=False)[source]¶
从整个组中收集张量到一个列表中。
tensor_list中的每个张量应位于不同的 GPU 上目前仅支持 nccl 后端 张量应仅为 GPU 张量
支持复数张量。
- Parameters:
output_tensor_lists (List[List[Tensor]]) –
输出列表。它应该 在每个GPU上包含正确大小的张量,用于集体操作的输出,例如
output_tensor_lists[i]包含驻留在input_tensor_list[i]的GPU上的all_gather结果。请注意,
output_tensor_lists的每个元素的大小为world_size * len(input_tensor_list),因为该函数会从组中的每个 GPU 收集结果。要解释output_tensor_lists[i]的每个元素,请注意input_tensor_list[j]的秩 k 会出现在output_tensor_lists[i][k * world_size + j]也请注意
len(output_tensor_lists),以及output_tensor_lists中每个元素的大小 (每个元素是一个列表,因此len(output_tensor_lists[i]))对于调用此函数的所有分布式进程必须相同。input_tensor_list (List[Tensor]) – 要从当前进程广播的张量列表(位于不同的GPU上)。 请注意,调用此函数的所有分布式进程中的
len(input_tensor_list)必须相同。组 (进程组, 可选) – 要操作的进程组。如果为None, 将使用默认的进程组。
async_op (bool, optional) – 此操作是否应为异步操作
- Returns:
异步工作句柄,如果 async_op 设置为 True。 如果没有设置 async_op 或者不属于该组,则为 None。
- torch.distributed.reduce_scatter_multigpu(output_tensor_list, input_tensor_lists, op=<RedOpType.SUM: 0>, group=None, async_op=False)[source]¶
将张量列表缩减并分散到整个组中。目前仅支持 nccl 后端。
每个张量在
output_tensor_list中应位于不同的 GPU 上,input_tensor_lists中的每个张量列表也应如此。- Parameters:
output_tensor_list (List[Tensor]) –
输出张量(位于不同的 GPU 上) 以接收操作的结果。
请注意
len(output_tensor_list)必须对于所有调用此函数的分布式进程保持一致。input_tensor_lists (List[List[Tensor]]) –
输入列表。它应该 在每个GPU上包含正确尺寸的张量,用于集体操作的输入,例如
input_tensor_lists[i]包含位于output_tensor_list[i]的GPU上的reduce_scatter输入。请注意,
input_tensor_lists的每个元素的大小为world_size * len(output_tensor_list),因为该函数会从组中的每个 GPU 分散结果。要理解input_tensor_lists[i]的每个元素,请注意output_tensor_list[j]的秩为 k 的进程会从input_tensor_lists[i][k * world_size + j]接收归约分散的结果。也请注意
len(input_tensor_lists),以及input_tensor_lists中每个元素的大小 (每个元素是一个列表,因此len(input_tensor_lists[i]))必须对于调用此函数的所有分布式进程都相同。组 (进程组, 可选) – 要操作的进程组。如果为None, 将使用默认的进程组。
async_op (bool, optional) – 此操作是否应为异步操作。
- Returns:
异步工作句柄,如果 async_op 设置为 True。 如果没有设置 async_op 或者不属于该组,则为 None。
第三方后端¶
除了内置的 GLOO/MPI/NCCL 后端,PyTorch 分布式通过运行时注册机制支持第三方后端。
有关如何通过 C++ 扩展开发第三方后端的参考资料,请参阅 教程 - 自定义 C++ 和 CUDA 扩展 和
test/cpp_extensions/cpp_c10d_extension.cpp。第三方后端的功能由其自身的实现决定。
新的后端继承自 c10d::ProcessGroup 并在导入时通过 torch.distributed.Backend.register_backend()
注册后端名称和实例化接口。
当手动导入此后端并使用相应的后端名称调用 torch.distributed.init_process_group()
时,torch.distributed 包将在新后端上运行。
警告
第三方后端的支持是实验性的,可能会发生变化。
启动工具¶
torch.distributed 包还提供了启动工具程序在 torch.distributed.launch。此辅助工具可用于为分布式训练在每个节点上启动多个进程。
torch.distributed.launch 是一个模块,它在每个训练节点上启动多个分布式
训练进程。
警告
此模块将被废弃,转而使用 torchrun。
该工具可用于单节点分布式训练,在这种情况下,每个节点将启动一个或多个进程。该工具可用于CPU训练或GPU训练。如果用于GPU训练,每个分布式进程将在单个GPU上运行。这可以显著提升单节点训练性能。它也可以用于多节点分布式训练,通过在每个节点上启动多个进程,从而显著提升多节点分布式训练性能。这对于具有多个Infiniband接口且支持直接GPU的系统尤其有益,因为所有接口都可以用于聚合通信带宽。
在单节点分布式训练或多节点分布式训练的情况下,此工具将在每个节点上启动给定数量的进程(--nproc-per-node)。如果用于GPU训练,这个数字需要小于或等于当前系统上的GPU数量(nproc_per_node),并且每个进程将在从 GPU 0 到 GPU (nproc_per_node - 1) 的单个GPU上运行。
如何使用此模块:
单节点多进程分布式训练
python -m torch.distributed.launch --nproc-per-node=NUM_GPUS_YOU_HAVE
YOUR_TRAINING_SCRIPT.py (--arg1 --arg2 --arg3 and all other
arguments of your training script)
多节点多进程分布式训练:(例如,两个节点)
节点 1: (IP: 192.168.1.1, 并且有一个空闲端口: 1234)
python -m torch.distributed.launch --nproc-per-node=NUM_GPUS_YOU_HAVE
--nnodes=2 --node-rank=0 --master-addr="192.168.1.1"
--master-port=1234 YOUR_TRAINING_SCRIPT.py (--arg1 --arg2 --arg3
and all other arguments of your training script)
节点2:
python -m torch.distributed.launch --nproc-per-node=NUM_GPUS_YOU_HAVE
--nnodes=2 --node-rank=1 --master-addr="192.168.1.1"
--master-port=1234 YOUR_TRAINING_SCRIPT.py (--arg1 --arg2 --arg3
and all other arguments of your training script)
要查找此模块提供的可选参数:
python -m torch.distributed.launch --help
重要通知:
此工具和多进程分布式(单节点或多节点)GPU训练目前仅在使用NCCL分布式后端时才能达到最佳性能。因此,对于GPU训练,建议使用NCCL后端。
2. 在你的训练程序中,你必须解析命令行参数:
--local-rank=LOCAL_PROCESS_RANK,该参数将由本模块提供。
如果你的训练程序使用GPU,你应该确保你的代码只在LOCAL_PROCESS_RANK对应的GPU设备上运行。这可以通过以下方式实现:
解析 local_rank 参数
>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument("--local-rank", type=int)
>>> args = parser.parse_args()
将您的设备设置为本地排名,使用以下任一方法
>>> torch.cuda.set_device(args.local_rank) # before your code runs
or
>>> with torch.cuda.device(args.local_rank):
>>> # your code to run
>>> ...
3. 在你的训练程序中,你应该在开始时调用以下函数来启动分布式后端。强烈建议使用init_method=env://。其他初始化方法(例如tcp://)可能有效,但env://是该模块正式支持的方法。
>>> torch.distributed.init_process_group(backend='YOUR BACKEND',
>>> init_method='env://')
4. 在你的训练程序中,你可以使用常规的分布式函数,或者使用 torch.nn.parallel.DistributedDataParallel() 模块。如果你的训练程序使用GPU进行训练,并且你希望使用 torch.nn.parallel.DistributedDataParallel() 模块,以下是配置方法。
>>> model = torch.nn.parallel.DistributedDataParallel(model,
>>> device_ids=[args.local_rank],
>>> output_device=args.local_rank)
请确保 device_ids 参数被设置为你的代码将要运行的唯一GPU设备ID。
这通常是进程的本地排名。换句话说,device_ids 需要是 [args.local_rank],
并且 output_device 需要是 args.local_rank 才能使用此工具
5. 另一种方法是通过环境变量将 local_rank 传递给子进程
LOCAL_RANK。当您使用
--use-env=True 启动脚本时,此行为会被启用。您必须调整上面的子进程示例,将
args.local_rank 替换为 os.environ['LOCAL_RANK'];指定此标志时,启动器不会传递 --local-rank。
警告
local_rank 并不是全局唯一的:它只是在一台机器上的每个进程中是唯一的。因此,不要用它来决定是否应该执行某些操作,例如,写入网络文件系统。请参见
https://github.com/pytorch/pytorch/issues/12042 了解如果处理不当可能会出现的问题。
生成工具¶
多进程包 - torch.multiprocessing 也提供了一个 spawn 函数在 torch.multiprocessing.spawn() 中。这个辅助函数可以用于生成多个进程。它的工作原理是传入你想要运行的函数,并生成 N 个进程来运行它。这也可以用于多进程分布式训练。
有关如何使用它的参考资料,请参阅 PyTorch 示例 - ImageNet 实现
请注意,此函数需要Python 3.4或更高版本。
调试 torch.distributed 应用程序¶
调试分布式应用程序可能具有挑战性,因为难以理解的挂起、崩溃或跨秩的不一致行为。torch.distributed 提供了一套工具,帮助以自助服务的方式调试训练应用程序:
监控屏障¶
从v1.10开始,torch.distributed.monitored_barrier() 作为 torch.distributed.barrier() 的替代品存在,后者在崩溃时会提供有关哪个秩可能出错的有用信息,即并非所有秩都在给定超时内调用 torch.distributed.monitored_barrier()。 torch.distributed.monitored_barrier() 使用类似于确认的过程中的 send/recv 通信原语实现主机端屏障,允许秩0报告哪些秩未能及时确认屏障。例如,考虑以下函数,其中秩1未能调用 torch.distributed.monitored_barrier()(实际上这可能是由于应用程序错误或先前集体操作中的挂起):
import os
from datetime import timedelta
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
def worker(rank):
dist.init_process_group("nccl", rank=rank, world_size=2)
# monitored barrier requires gloo process group to perform host-side sync.
group_gloo = dist.new_group(backend="gloo")
if rank not in [1]:
dist.monitored_barrier(group=group_gloo, timeout=timedelta(seconds=2))
if __name__ == "__main__":
os.environ["MASTER_ADDR"] = "localhost"
os.environ["MASTER_PORT"] = "29501"
mp.spawn(worker, nprocs=2, args=())
以下错误消息在秩0上生成,允许用户确定哪些秩可能存在问题并进一步调查:
RuntimeError: Rank 1 failed to pass monitoredBarrier in 2000 ms
Original exception:
[gloo/transport/tcp/pair.cc:598] Connection closed by peer [2401:db00:eef0:1100:3560:0:1c05:25d]:8594
TORCH_DISTRIBUTED_DEBUG¶
使用 TORCH_CPP_LOG_LEVEL=INFO,环境变量 TORCH_DISTRIBUTED_DEBUG 可以用来触发额外的有用日志记录和集体同步检查,以确保所有秩都适当同步。 TORCH_DISTRIBUTED_DEBUG 可以设置为 OFF(默认),INFO 或 DETAIL,具体取决于所需的调试级别。请注意,最详细选项 DETAIL 可能会影响应用程序性能,因此仅在调试问题时使用。
设置 TORCH_DISTRIBUTED_DEBUG=INFO 将在使用 torch.nn.parallel.DistributedDataParallel() 训练的模型初始化时生成额外的调试日志,并且
TORCH_DISTRIBUTED_DEBUG=DETAIL 还将记录选定迭代次数的运行时性能统计信息。这些运行时统计信息
包括前向时间、后向时间、梯度通信时间等数据。例如,给定以下应用程序:
import os
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
class TwoLinLayerNet(torch.nn.Module):
def __init__(self):
super().__init__()
self.a = torch.nn.Linear(10, 10, bias=False)
self.b = torch.nn.Linear(10, 1, bias=False)
def forward(self, x):
a = self.a(x)
b = self.b(x)
return (a, b)
def worker(rank):
dist.init_process_group("nccl", rank=rank, world_size=2)
torch.cuda.set_device(rank)
print("init model")
model = TwoLinLayerNet().cuda()
print("init ddp")
ddp_model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[rank])
inp = torch.randn(10, 10).cuda()
print("train")
for _ in range(20):
output = ddp_model(inp)
loss = output[0] + output[1]
loss.sum().backward()
if __name__ == "__main__":
os.environ["MASTER_ADDR"] = "localhost"
os.environ["MASTER_PORT"] = "29501"
os.environ["TORCH_CPP_LOG_LEVEL"]="INFO"
os.environ[
"TORCH_DISTRIBUTED_DEBUG"
] = "DETAIL" # set to DETAIL for runtime logging.
mp.spawn(worker, nprocs=2, args=())
以下日志在初始化时生成:
I0607 16:10:35.739390 515217 logger.cpp:173] [Rank 0]: DDP Initialized with:
broadcast_buffers: 1
bucket_cap_bytes: 26214400
find_unused_parameters: 0
gradient_as_bucket_view: 0
is_multi_device_module: 0
iteration: 0
num_parameter_tensors: 2
output_device: 0
rank: 0
total_parameter_size_bytes: 440
world_size: 2
backend_name: nccl
bucket_sizes: 440
cuda_visible_devices: N/A
device_ids: 0
dtypes: float
master_addr: localhost
master_port: 29501
module_name: TwoLinLayerNet
nccl_async_error_handling: N/A
nccl_blocking_wait: N/A
nccl_debug: WARN
nccl_ib_timeout: N/A
nccl_nthreads: N/A
nccl_socket_ifname: N/A
torch_distributed_debug: INFO
以下日志在运行时生成(当 TORCH_DISTRIBUTED_DEBUG=DETAIL 被设置时):
I0607 16:18:58.085681 544067 logger.cpp:344] [Rank 1 / 2] Training TwoLinLayerNet unused_parameter_size=0
Avg forward compute time: 40838608
Avg backward compute time: 5983335
Avg backward comm. time: 4326421
Avg backward comm/comp overlap time: 4207652
I0607 16:18:58.085693 544066 logger.cpp:344] [Rank 0 / 2] Training TwoLinLayerNet unused_parameter_size=0
Avg forward compute time: 42850427
Avg backward compute time: 3885553
Avg backward comm. time: 2357981
Avg backward comm/comp overlap time: 2234674
此外,TORCH_DISTRIBUTED_DEBUG=INFO 在 torch.nn.parallel.DistributedDataParallel() 中增强了崩溃日志记录,因为模型中存在未使用的参数。目前,如果在前向传递过程中可能有未使用的参数,则必须将 find_unused_parameters=True 传递给 torch.nn.parallel.DistributedDataParallel() 初始化,并且从 v1.10 开始,所有模型输出都必须用于损失计算,因为 torch.nn.parallel.DistributedDataParallel() 不支持在反向传递中使用未使用的参数。这些约束对于较大的模型来说尤其具有挑战性,因此当出现错误时,torch.nn.parallel.DistributedDataParallel() 将记录所有未使用参数的全限定名称。例如,在上述应用程序中,如果我们修改 loss 以计算为 loss = output[1],则 TwoLinLayerNet.a 在反向传递中不会接收到梯度,从而导致 DDP 失败。在崩溃时,用户会收到有关未使用参数的信息,这对于大型模型来说可能很难手动查找:
RuntimeError: Expected to have finished reduction in the prior iteration before starting a new one. This error indicates that your module has parameters that were not used in producing loss. You can enable unused parameter detection by passing
the keyword argument `find_unused_parameters=True` to `torch.nn.parallel.DistributedDataParallel`, and by
making sure all `forward` function outputs participate in calculating loss.
If you already have done the above, then the distributed data parallel module wasn't able to locate the output tensors in the return value of your module's `forward` function. Please include the loss function and the structure of the return va
lue of `forward` of your module when reporting this issue (e.g. list, dict, iterable).
Parameters which did not receive grad for rank 0: a.weight
Parameter indices which did not receive grad for rank 0: 0
设置 TORCH_DISTRIBUTED_DEBUG=DETAIL 将在用户发出的每个集体调用上触发额外的一致性和同步检查,无论是直接还是间接(如 DDP allreduce)。这是通过创建一个包装进程组来实现的,该进程组包装了由
torch.distributed.init_process_group() 和 torch.distributed.new_group() API 返回的所有进程组。因此,这些API将返回一个可以像普通进程组一样使用的包装进程组,但在将集体分派到底层进程组之前执行一致性检查。目前,这些检查包括一个 torch.distributed.monitored_barrier(),
它确保所有秩完成其未决的集体调用,并报告卡住的秩。接下来,通过确保所有集体函数匹配并且以一致的张量形状被调用来检查集体本身的一致性。如果不是这种情况,则会在应用程序崩溃时包含详细的错误报告,而不是挂起或无信息的错误消息。例如,考虑以下函数,其中输入形状与
torch.distributed.all_reduce() 不匹配:
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
def worker(rank):
dist.init_process_group("nccl", rank=rank, world_size=2)
torch.cuda.set_device(rank)
tensor = torch.randn(10 if rank == 0 else 20).cuda()
dist.all_reduce(tensor)
torch.cuda.synchronize(device=rank)
if __name__ == "__main__":
os.environ["MASTER_ADDR"] = "localhost"
os.environ["MASTER_PORT"] = "29501"
os.environ["TORCH_CPP_LOG_LEVEL"]="INFO"
os.environ["TORCH_DISTRIBUTED_DEBUG"] = "DETAIL"
mp.spawn(worker, nprocs=2, args=())
使用NCCL后端,这样的应用程序可能会导致挂起,在非平凡场景中很难找到根本原因。如果用户启用了TORCH_DISTRIBUTED_DEBUG=DETAIL并重新运行应用程序,则以下错误消息揭示了根本原因:
work = default_pg.allreduce([tensor], opts)
RuntimeError: Error when verifying shape tensors for collective ALLREDUCE on rank 0. This likely indicates that input shapes into the collective are mismatched across ranks. Got shapes: 10
[ torch.LongTensor{1} ]
注意
为了在运行时对调试级别进行细粒度控制,还可以使用函数torch.distributed.set_debug_level()、torch.distributed.set_debug_level_from_env()和torch.distributed.get_debug_level()。
此外,TORCH_DISTRIBUTED_DEBUG=DETAIL 可以与TORCH_SHOW_CPP_STACKTRACES=1 结合使用,在检测到集体去同步时记录整个调用堆栈。这些集体去同步检查适用于所有使用c10d 集体调用的应用程序,这些调用由使用torch.distributed.init_process_group() 和torch.distributed.new_group() API 创建的过程组支持。
日志记录¶
除了通过 torch.distributed.monitored_barrier() 和 TORCH_DISTRIBUTED_DEBUG 提供的显式调试支持外,torch.distributed 的底层 C++ 库还会在不同级别输出日志消息。这些消息有助于理解分布式训练任务的执行状态,并解决诸如网络连接失败等问题。以下矩阵显示了如何通过组合 TORCH_CPP_LOG_LEVEL 和 TORCH_DISTRIBUTED_DEBUG 环境变量来调整日志级别。
|
|
有效的日志级别 |
|---|---|---|
|
忽略 |
错误 |
|
忽略 |
警告 |
|
忽略 |
信息 |
|
|
调试 |
|
|
跟踪(也称为全部) |
Distributed 有一个自定义的异常类型,它继承自 RuntimeError,称为 torch.distributed.DistBackendError。当发生后端特定错误时,会抛出此异常。例如,如果使用了 NCCL 后端,而用户尝试使用一个不可用于 NCCL 库的 GPU。
- class torch.distributed.DistBackendError¶
当分布式后端发生错误时引发的异常
警告
DistBackendError 异常类型是一个实验性功能,可能会发生变化。