目录

分布式通信包 - torch.distributed

注意

请参阅PyTorch 分布式概述 ,以获取有关分布式训练所有功能的简要介绍。

后端

torch.distributed 支持三种内置后端,每种后端具有不同的功能。下表显示了哪些函数可用于 CPU / CUDA 张量。 如果用于构建 PyTorch 的实现支持 CUDA,则 MPI 仅支持 CUDA。

后端

gloo

mpi

nccl

设备

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=eth0

  • GLOO_SOCKET_IFNAME, 例如 export GLOO_SOCKET_IFNAME=eth0

如果你使用的是Gloo后端,可以通过用逗号分隔来指定多个接口,如下所示: export GLOO_SOCKET_IFNAME=eth0,eth1,eth2,eth3。 后端将以轮询方式在这些接口之间分发操作。 所有进程必须在此变量中指定相同数量的接口,这是至关重要的。

其他NCCL环境变量

NCCL 还提供了一些环境变量,用于微调目的。

常用的包括以下内容,用于调试目的:

  • export NCCL_DEBUG=INFO

  • export NCCL_DEBUG_SUBSYS=ALL

有关NCCL环境变量的完整列表,请参阅 NVIDIA NCCL的官方文档

基础

The torch.distributed 包提供了 PyTorch 支持和通信原语,用于在一台或多台机器上的多个计算节点之间实现多进程并行。类 torch.nn.parallel.DistributedDataParallel() 基于此功能,作为任何 PyTorch 模型的包装器,提供同步分布式训练。这与 多进程包 - torch.multiprocessingtorch.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

torch.distributed.init_process_group(backend, init_method=None, timeout=datetime.timedelta(0, 1800), world_size=- 1, rank=- 1, store=None, group_name='', pg_options=None)[source]

初始化默认的分布式进程组,这也将初始化分布式包。

There are 2 main ways to initialize a process group:
  1. 明确指定 storerankworld_size

  2. 指定 init_method(一个URL字符串),指示在哪里/如何 发现对等节点。可选地指定 rankworld_size, 或将所有必需的参数编码在URL中并省略它们。

如果两者都没有指定,则假定init_method为“env://”。

Parameters
  • 后端 (strBackend) – 要使用的后端。根据 构建时的配置,有效值包括 mpi, gloo, 和 nccl。此字段应作为小写字符串提供 (例如,"gloo"),也可以通过 Backend 属性访问 (例如,Backend.GLOO)。如果使用 每台机器上的多个进程与 nccl 后端,每个进程 必须独占访问其使用的每个 GPU,因为在进程之间共享 GPU 可能导致死锁。

  • init_method (str, 可选) – 指定如何初始化进程组的URL。默认情况下,如果未指定init_methodstore,则为“env://”。与store互斥。

  • world_size (int, 可选) – 参与任务的进程数量。如果指定了store,则为必填项。

  • 排名 (int, 可选) – 当前进程的排名(应为0到world_size-1之间的数字)。 如果指定了store,则为必填项。

  • 存储 (存储可选) – 所有工作者均可访问的键/值存储,用于交换连接/地址信息。 与 init_method 互斥。

  • 超时 (timedelta, 可选) – 对进程组执行操作的超时时间。默认值等于30分钟。 这适用于 gloo 后端。对于 nccl,只有在环境变量 NCCL_BLOCKING_WAITNCCL_ASYNC_ERROR_HANDLING 设置为 1 时才适用。当 NCCL_BLOCKING_WAIT 被设置时,这是进程将阻塞并等待集合操作完成的时间长度 在抛出异常之前。当 NCCL_ASYNC_ERROR_HANDLING 被设置时, 这是集合操作将在之后被异步中止的时间长度,并且进程将崩溃。 NCCL_BLOCKING_WAIT 将向用户提供错误信息,这些错误可以被捕获和处理,但由于其阻塞特性,它会有性能开销。另一方面,NCCL_ASYNC_ERROR_HANDLING 的性能开销非常小, 但在出现错误时会崩溃进程。这是由于CUDA执行是异步的,继续执行用户代码不再安全,因为失败的异步NCCL操作可能导致后续CUDA操作在损坏的数据上运行。这两个环境变量中应只设置其中一个。

  • group_name (str, 可选, 已弃用) – 组名。

  • pg_options (ProcessGroupOptions, 可选) – 进程组选项 指定在构建特定进程组时需要传递的其他选项。目前,我们唯一支持的选项是 ProcessGroupNCCL.Options 用于 nccl 后端,is_high_priority_stream 可以指定以便 当有计算内核等待时,nccl 后端可以拾取高优先级的 cuda 流。

注意

要启用 backend == Backend.MPI,需要在支持MPI的系统上从源代码构建PyTorch。

torch.distributed.is_initialized()[source]

检查默认进程组是否已初始化

torch.distributed.is_mpi_available()[source]

检查 MPI 后端是否可用。

torch.distributed.is_nccl_available()[source]

检查 NCCL 后端是否可用。

torch.distributed.is_torchelastic_launched()[source]

检查此进程是否使用torch.distributed.elastic (即 torchelastic)启动。通过是否存在 TORCHELASTIC_RUN_ID 环境 变量来判断当前进程是否使用 torchelastic 启动。这是一个合理的代理方式,因为 TORCHELASTIC_RUN_ID 映射到 rendezvous id,该值始终为非空值,用于表示作业 ID 以便对等发现。


目前支持三种初始化方法:

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)

共享文件系统初始化

另一种初始化方法使用一个在组中所有机器上共享和可见的文件系统,以及所需的world_size。URL应以file://开头,并包含指向共享文件系统上不存在文件(在现有目录中)的路径。文件系统初始化将自动创建该文件(如果它不存在),但不会删除该文件。因此,在下次在同一文件路径/名称上调用init_process_group()之前,确保清理该文件是你的责任。

请注意,在最新的分布式包中不再支持自动排名分配,并且group_name也被弃用了。

警告

此方法假设文件系统支持使用 fcntl 进行锁定 - 大多数本地系统和NFS都支持它。

警告

此方法将始终创建文件,并在程序结束时尽力清理并删除该文件。换句话说,每次使用文件初始化方法进行初始化时,都需要一个全新的空文件才能成功初始化。如果再次使用之前初始化使用的同一文件(由于某种原因未被清理),这将导致意外行为,并且经常会导致死锁和失败。因此,尽管此方法会尽力清理文件,但如果自动删除未能成功,则需要您确保在训练结束时删除该文件,以防止在下次使用时重复使用同一文件。如果您计划在同一文件名上调用 init_process_group() 多次,这一点尤为重要。 换句话说,如果文件未被删除或清理,并且再次在该文件上调用 init_process_group(),则预计会出现故障。 这里的基本原则是,在每次调用 init_process_group() 时,确保文件不存在或为空。

import torch.distributed as dist

# rank should always be specified
dist.init_process_group(backend, init_method='file:///mnt/nfs/sharedfile',
                        world_size=4, rank=args.rank)

环境变量初始化

此方法将从环境变量中读取配置,允许完全自定义信息的获取方式。需要设置的变量为:

  • 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、MPI 以及其他已注册的后端。

这个类的值是小写字符串,例如,"gloo"。它们可以通过属性访问,例如,Backend.NCCL

这个类可以直接调用来解析字符串,例如, Backend(backend_str) 将检查 backend_str 是否有效,并 如果有效则返回解析后的小写字符串。它还接受大写字符串, 例如,Backend("GLOO") 返回 "gloo"

注意

条目 Backend.UNDEFINED 存在,但仅用作某些字段的初始值。用户不应直接使用它,也不应假设其存在。

torch.distributed.get_backend(group=None)[source]

返回给定进程组的后端。

Parameters

(进程组, 可选) – 要工作的进程组。默认是通用主进程组。如果指定了另一个特定的组,则调用进程必须是group的一部分。

Returns

给定进程组的后端作为一个小写字符串。

torch.distributed.get_rank(group=None)[source]

返回当前进程在提供的 group 中的排名或 默认组,如果没有提供的话。

排名是分配给分布式进程组中每个进程的唯一标识符。它们总是从0到 world_size的连续整数。

Parameters

(进程组, 可选) – 要操作的进程组。如果为None, 将使用默认的进程组。

Returns

进程组的秩 -1,如果不是组的一部分

torch.distributed.get_world_size(group=None)[source]

返回当前进程组中的进程数量。

Parameters

(进程组, 可选) – 要操作的进程组。如果为None, 将使用默认的进程组。

Returns

进程组的世界大小 -1,如果不是组的一部分


分布式键值存储

分布式包附带了一个分布式键值存储,可以用于在组中的进程之间共享信息以及初始化分布式包在 torch.distributed.init_process_group()(通过显式创建存储作为指定init_method的替代方案。)有3种选择用于键值存储:TCPStore, FileStore, 和 HashStore

class torch.distributed.Store

所有存储实现的基类,例如PyTorch分布式提供的3种实现:(TCPStore, FileStore, 和 HashStore)。

class torch.distributed.TCPStore

基于TCP的分布式键值存储实现。服务器存储持有数据,而客户端存储可以通过TCP连接到服务器存储并执行诸如set()插入键值对,get()检索键值对等操作。应该始终初始化一个服务器存储,因为客户端存储将等待服务器建立连接。

Parameters
  • 主机名 (str) – 服务器存储应运行的主机名或IP地址。

  • 端口 (int) – 服务器存储应监听传入请求的端口。

  • world_size (int, optional) – 存储用户的总数(客户端数量 + 1 用于服务器)。默认值为 -1(负值表示存储用户数量不固定)。

  • 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

一种使用文件来存储底层键值对的存储实现。

Parameters
  • 文件名 (str) – 存储键值对的文件路径

  • world_size (int, 可选) – 使用存储的进程总数。默认值为 -1(负值表示存储用户数量不固定)。

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

将键值对插入存储中,基于提供的keyvalue。如果key已经在存储中存在,它将用新提供的value覆盖旧值。

Parameters
  • (str) – 要添加到存储中的键。

  • (str) – 与 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.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()将会导致异常。

Parameters
  • (str) – 存储中将要递增计数器的键。

  • 数量 (int) – 计数器将要增加的数量。

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_valuedesired_value之间的比较。desired_value仅在key已经存在于存储中或expected_value为空字符串时才会被设置。

Parameters
  • (str) – 需要在存储中检查的键。

  • 预期值 (str) – 在插入之前要检查的与 key 关联的值。

  • 期望值 (str) – 与 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("key", "first_value")
>>> store.compare_set("key", "first_value", "second_value")
>>> # Should return "second_value"
>>> store.get("key")
torch.distributed.Store.wait(*args, **kwargs)

重载函数。

  1. 等待(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"])
  1. 等待(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

警告

这个 delete_key API 仅由 TCPStoreHashStore 支持。使用此API 与 FileStore 将导致异常。

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(0, 1800), backend=None, pg_options=None)[source]

创建一个新的分布式组。

此函数要求主组中的所有进程(即分布式作业的所有组成部分)都进入此函数,即使它们不会成为该组的成员。此外,所有进程中应以相同的顺序创建组。

警告

同时使用多个进程组与NCCL后端并发是不安全的,用户应在应用程序中执行显式同步以确保一次只使用一个进程组。这意味着来自一个进程组的集体操作应在设备上完成执行(不仅仅是排队,因为CUDA执行是异步的),然后才能将来自另一个进程组的集体操作排队。有关详细信息,请参见并发使用多个NCCL通信器

Parameters
  • 等级 (列表[整数]) – 群组成员的等级列表。如果为None,则将设置为所有等级。默认值为None

  • 超时 (timedelta, 可选) – 对进程组执行操作的超时时间。默认值等于30分钟。 这适用于 gloo 后端。对于 nccl,只有在环境变量 NCCL_BLOCKING_WAITNCCL_ASYNC_ERROR_HANDLING 设置为 1 时才适用。当 NCCL_BLOCKING_WAIT 被设置时,这是进程将阻塞并等待集合操作完成的时间长度 在抛出异常之前。当 NCCL_ASYNC_ERROR_HANDLING 被设置时, 这是集合操作将在之后被异步中止的时间长度,并且进程将崩溃。 NCCL_BLOCKING_WAIT 将向用户提供错误信息,这些错误可以被捕获和处理,但由于其阻塞特性,它会有性能开销。另一方面,NCCL_ASYNC_ERROR_HANDLING 的性能开销非常小, 但在出现错误时会崩溃进程。这是由于CUDA执行是异步的,继续执行用户代码不再安全,因为失败的异步NCCL操作可能导致后续CUDA操作在损坏的数据上运行。这两个环境变量中应只设置其中一个。

  • 后端 (strBackend, 可选) – 要使用的后端。根据构建时的配置,有效值为 gloonccl。 默认情况下使用与全局组相同的后端。此字段应以小写字符串形式给出(例如,"gloo"),也可以通过 Backend 属性访问(例如, Backend.GLOO)。如果传递了 None,则将使用默认进程组对应的后端。默认值为 None

  • pg_options (ProcessGroupOptions, 可选) – 进程组选项 指定在构建特定进程组时需要传递的其他选项。例如,对于nccl 后端,可以指定is_high_priority_stream,以便 进程组可以选择高优先级的cuda流。

Returns

可用于集体调用的分布式组的句柄。

点对点通信

torch.distributed.send(tensor, dst, group=None, tag=0)[source]

同步发送一个张量。

Parameters
  • 张量 (张量) – 要发送的张量。

  • dst (int) – 目标等级。

  • (进程组, 可选) – 要操作的进程组。如果为None, 将使用默认的进程组。

  • 标签 (int, 可选) – 用于与远程接收匹配的发送标签

torch.distributed.recv(tensor, src=None, group=None, tag=0)[source]

同步接收一个张量。

Parameters
  • 张量 (张量) – 用于填充接收到的数据的张量。

  • src (int, optional) – 源进程的等级。如果未指定,将从任何进程接收。

  • (进程组, 可选) – 要操作的进程组。如果为None, 将使用默认的进程组。

  • 标签 (int, 可选) – 用于匹配远程发送的接收标签

Returns

发送者排名 -1,如果不是组的一部分

isend()irecv() 在使用时返回分布式请求对象。一般来说,这种对象的类型是未指定的 因为它们不应该手动创建,但可以保证支持两种方法:

  • is_completed() - 如果操作已完成,则返回True

  • wait() - 将阻塞进程,直到操作完成。 is_completed() 保证一旦返回则返回True。

torch.distributed.isend(tensor, dst, group=None, tag=0)[source]

异步发送一个张量。

警告

在请求完成之前修改tensor会导致未定义的行为。

Parameters
  • 张量 (张量) – 要发送的张量。

  • dst (int) – 目标等级。

  • (进程组, 可选) – 要操作的进程组。如果为None, 将使用默认的进程组。

  • 标签 (int, 可选) – 用于与远程接收匹配的发送标签

Returns

一个分布式请求对象。 如果不属于该组,则为None。

torch.distributed.irecv(tensor, src=None, group=None, tag=0)[source]

异步接收一个张量。

Parameters
  • 张量 (张量) – 用于填充接收到的数据的张量。

  • src (int, optional) – 源进程的等级。如果未指定,将从任何进程接收。

  • (进程组, 可选) – 要操作的进程组。如果为None, 将使用默认的进程组。

  • 标签 (int, 可选) – 用于匹配远程发送的接收标签

Returns

一个分布式请求对象。 如果不属于该组,则为None。

同步和异步集体操作

每个集体操作函数支持以下两种操作,具体取决于传递给集体的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 必须在所有参与集体操作的进程中具有相同数量的元素。

Parameters
  • 张量 (张量) – 如果当前进程的等级为src,则为要发送的数据;否则为用于保存接收到的数据的张量。

  • src (int) – 源张量的秩(维度数)。

  • (进程组, 可选) – 要操作的进程组。如果为None, 将使用默认的进程组。

  • async_op (bool, optional) – 此操作是否应为异步操作

Returns

异步工作句柄,如果 async_op 设置为 True。 如果没有设置 async_op 或者不属于该组,则为 None。

torch.distributed.broadcast_object_list(object_list, src=0, group=None, device=None)[source]

Broadcasts picklable objects in object_list to the whole group. Similar to broadcast(), but Python objects can be passed in. Note that all objects in object_list must 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)
>>> broadcast_objects
['foo', 12, {1: 2}]
torch.distributed.all_reduce(tensor, op=<ReduceOp.SUM: 0>, group=None, async_op=False)[source]

在所有机器之间减少张量数据,使得所有机器都得到最终结果。

调用后 tensor 在所有进程中将逐位完全相同。

支持复数张量。

Parameters
  • 张量 (Tensor) – 集体操作的输入和输出。该函数 在原地进行操作。

  • 操作 (可选) – 以下值之一 torch.distributed.ReduceOp 枚举。指定用于元素级归约的操作。

  • (进程组, 可选) – 要操作的进程组。如果为None, 将使用默认的进程组。

  • async_op (bool, optional) – 此操作是否应为异步操作

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=<ReduceOp.SUM: 0>, group=None, async_op=False)[source]

在所有机器上减少张量数据。

只有排名为 dst 的进程将接收最终结果。

Parameters
  • 张量 (Tensor) – 集体操作的输入和输出。该函数 在原地进行操作。

  • dst (int) – 目标等级

  • 操作 (可选) – 以下值之一 torch.distributed.ReduceOp 枚举。指定用于元素级归约的操作。

  • (进程组, 可选) – 要操作的进程组。如果为None, 将使用默认的进程组。

  • async_op (bool, optional) – 此操作是否应为异步操作

Returns

异步工作句柄,如果 async_op 设置为 True。 如果没有设置 async_op 或者不属于该组,则为 None。

torch.distributed.all_gather(tensor_list, tensor, group=None, async_op=False)[source]

从整个组中收集张量并放入列表中。

支持复数张量。

Parameters
  • tensor_list (list[Tensor]) – 输出列表。它应该包含正确大小的张量,用于集体操作的输出。

  • 张量 (张量) – 从当前进程广播的张量。

  • (进程组, 可选) – 要操作的进程组。如果为None, 将使用默认的进程组。

  • async_op (bool, optional) – 此操作是否应为异步操作

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_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]

在单个进程中收集一组张量。

Parameters
  • 张量 (张量) – 输入张量。

  • gather_list (list[Tensor], optional) – 用于收集数据的适当大小的张量列表(默认为None,必须在目标秩上指定)

  • dst (int, 可选) – 目标进程的编号 (默认为 0)

  • (进程组, 可选) – 要操作的进程组。如果为None, 将使用默认的进程组。

  • async_op (bool, optional) – 此操作是否应为异步操作

Returns

异步工作句柄,如果 async_op 设置为 True。 如果没有设置 async_op 或者不属于该组,则为 None。

torch.distributed.gather_object(obj, object_gather_list=None, dst=0, group=None)[source]

从整个组中在一个进程中收集可序列化的对象。 类似于 gather(),但可以传入Python对象。请注意,对象必须是可序列化的才能被收集。

Parameters
  • 对象 (任意类型) – 输入对象。必须是可pickle的。

  • object_gather_list (list[Any]) – 输出列表。在 dst 级别上,它 应该正确地调整为该集体操作组的大小,并将包含输出。必须在非目标 级别上为 None。(默认值为 None

  • dst (int, 可选) – 目标进程的等级。 (默认为 0)

  • – (进程组,可选):要操作的进程组。如果为None,则将使用默认进程组。默认值是 None

Returns

无。在dst排名中,object_gather_list将包含集体操作的输出。

注意

请注意,此API与gather集体操作略有不同 因为它不提供异步操作句柄,因此将是一个阻塞调用。

注意

请注意,当使用 NCCL 后端时,此 API 不受支持。

警告

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
  • 张量 (张量) – 输出张量。

  • scatter_list (list[Tensor]) – 要分发的张量列表(默认为 None,必须在源秩上指定)

  • src (int) – 源等级(默认为 0)

  • (进程组, 可选) – 要操作的进程组。如果为None, 将使用默认的进程组。

  • async_op (bool, optional) – 此操作是否应为异步操作

Returns

异步工作句柄,如果 async_op 设置为 True。 如果没有设置 async_op 或者不属于该组,则为 None。

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=<ReduceOp.SUM: 0>, group=None, async_op=False)[source]

减少,然后将一组张量列表分散到所有进程中。

Parameters
  • 输出 (张量) – 输出张量。

  • input_list (list[Tensor]) – 需要归约和分散的张量列表。

  • (进程组, 可选) – 要操作的进程组。如果为None, 将使用默认的进程组。

  • async_op (bool, optional) – 此操作是否应为异步操作。

Returns

异步工作句柄,如果 async_op 设置为 True。 如果没有设置 async_op 或者不属于该组,则为 None。

torch.distributed.all_to_all(output_tensor_list, input_tensor_list, group=None, async_op=False)[source]

每个进程将输入张量列表分散到组内的所有进程中,并在输出列表中返回收集到的张量列表。

支持复数张量。

Parameters
  • output_tensor_list (list[Tensor]) – 要收集的张量列表,每个秩一个。

  • input_tensor_list (list[Tensor]) – 每个秩分散一个张量的张量列表。

  • (进程组, 可选) – 要操作的进程组。如果为None, 将使用默认的进程组。

  • async_op (bool, optional) – 此操作是否应为异步操作。

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() 时。

Parameters
  • (进程组, 可选) – 要操作的进程组。如果为None, 将使用默认的进程组。

  • async_op (bool, optional) – 此操作是否应为异步操作

  • device_ids ([int], optional) – 设备/GPU id 的列表。 仅在 NCCL 后端有效。

Returns

异步工作句柄,如果 async_op 设置为 True。 如果没有设置 async_op 或者不属于该组,则为 None。

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 (布尔值, 可选) – 是否收集所有失败的等级。默认情况下,此值为 Falsemonitored_barrier,在等级 0 上遇到第一个失败的等级时会快速失败并抛出错误。通过设置 wait_all_ranks=True monitored_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

请注意 BAND, BOR, 和 BXOR 的缩减方式在使用 NCCL 后端时不可用。

此外,MAXMINPRODUCT不支持复数张量。

该类的值可以作为属性访问,例如,ReduceOp.SUM。 它们用于指定归约集合的策略,例如, reduce(), all_reduce_multigpu() 等。

Members:

SUM

PRODUCT

MIN

MAX

BAND

BOR

BXOR

class torch.distributed.reduce_op

已弃用的枚举类用于减少操作: SUM, PRODUCT, MIN, 和 MAX

ReduceOp 建议使用它代替。

集体通信性能分析

请注意,您可以使用 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)

请参阅分析器文档以获取分析器功能的完整概述。

支持Autograd的通信原语

如果你想使用支持autograd的集合通信函数 你可以在 torch.distributed.nn.* 模块中找到这些实现。

此处的函数是同步的,会被插入到 autograd 图中,因此你需要确保参与集体操作的所有进程都会执行反向传播,以使反向通信有效进行,并避免死锁。

请注意,目前唯一能保证所有功能正常工作的后端是 gloo. .. autofunction:: torch.distributed.nn.broadcast .. autofunction:: torch.distributed.nn.gather .. autofunction:: torch.distributed.nn.scatter .. autofunction:: torch.distributed.nn.reduce .. autofunction:: torch.distributed.nn.all_gather .. autofunction:: torch.distributed.nn.all_to_all .. autofunction:: torch.distributed.nn.all_reduce

多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=<ReduceOp.SUM: 0>, group=None, async_op=False)[source]

在所有机器之间减少张量数据,使得所有机器都能得到最终结果。此函数在每个节点上减少多个张量,而每个张量位于不同的 GPU 上。 因此,张量列表中的输入张量需要是 GPU 张量。 此外,张量列表中的每个张量都需要位于不同的 GPU 上。

调用之后,所有 tensortensor_list 中都会在所有进程中按位完全相同。

支持复数张量。

目前仅支持 nccl 和 gloo 后端 张量应仅为 GPU 张量

Parameters
  • tensor_list (List[Tensor]) – 集合操作的输入和输出张量列表。该函数在原地操作,并要求每个张量都是位于不同GPU上的GPU张量。 你还需要确保调用此函数的所有分布式进程中的 len(tensor_list) 是相同的。

  • 操作 (可选) – 以下值之一 torch.distributed.ReduceOp 枚举。指定用于元素级归约的操作。

  • (进程组, 可选) – 要操作的进程组。如果为 None,将使用默认的进程组。

  • async_op (bool, optional) – 此操作是否应为异步操作

Returns

异步工作句柄,如果 async_op 设置为 True。 如果没有设置 async_op 或者不属于该组,则为 None。

torch.distributed.reduce_multigpu(tensor_list, dst, op=<ReduceOp.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=<ReduceOp.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上运行。

如何使用此模块:

  1. 单节点多进程分布式训练

>>> 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. 多节点多进程分布式训练:(例如,两个节点)

节点 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)
  1. 要查找此模块提供的可选参数:

>>> 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_DISTRIBUTED_DEBUG 可设置为 OFF(默认)、INFODETAIL,具体取决于所需的调试级别。请注意,最详细的选项 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_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=INFOtorch.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_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_DEBUG=DETAIL 可以与TORCH_SHOW_CPP_STACKTRACES=1 结合使用,在检测到集体去同步时记录整个调用堆栈。这些集体去同步检查适用于所有使用c10d 集体调用的应用程序,这些调用由使用torch.distributed.init_process_group()torch.distributed.new_group() API 创建的过程组支持。

文档

访问 PyTorch 的全面开发人员文档

查看文档

教程

获取面向初学者和高级开发人员的深入教程

查看教程

资源

查找开发资源并解答您的问题

查看资源