PyTorch 入门指南
学习 PyTorch
图像和视频
音频
后端
强化学习
在生产环境中部署 PyTorch 模型
Profiling PyTorch
代码变换与FX
前端API
扩展 PyTorch
模型优化
并行和分布式训练
边缘端的 ExecuTorch
推荐系统
多模态

使用 Join 上下文管理器进行不均匀输入的分布式训练

作者: Andrew Gu

Join 在 PyTorch 1.10 中作为原型功能引入。该 API 可能会发生变化。

在本教程中,您将了解到:

  • Join 上下文管理器的概述。

  • 一个关于如何使用 DistributedDataParallel 与上下文管理器的示例。

  • 一个关于如何同时使用 DistributedDataParallelZeroRedundancyOptimizer 与上下文管理器的示例。

  • 一个关于如何向上下文管理器传递关键字参数的示例。

  • 深入探讨 Join 上下文管理器的工作原理。

  • 一个展示如何使一个玩具类与上下文管理器兼容的示例。

什么是 Join

分布式数据并行入门 - 基本用例中,您已经了解了使用DistributedDataParallel进行数据并行训练的基本框架。该框架会在每个反向传播中隐式地调度全归约操作,以同步跨进程的梯度。这种集体通信需要进程组中的所有进程参与,因此如果某个进程的输入较少,其他进程将会挂起或报错(具体取决于所使用的后端)。更一般地说,这种问题在任何执行每轮迭代同步集体通信的类中都会持续存在。

Join 是一个上下文管理器,用于包装每个进程的训练循环,以便在输入不均衡的情况下进行训练。该上下文管理器允许那些提前耗尽输入的进程(即提前 join 的进程)对其他尚未加入的进程所执行的集体通信进行影子操作。通信的影子操作方式由钩子函数指定。

DistributedDataParallel 中使用 Join

PyTorch 的 DistributedDataParallelJoin 上下文管理器开箱即用。以下是一个示例用法:

importos
importtorch
importtorch.distributedasdist
importtorch.multiprocessingasmp
fromtorch.distributed.algorithms.joinimport Join
fromtorch.nn.parallelimport DistributedDataParallel as DDP

BACKEND = "nccl"
WORLD_SIZE = 2
NUM_INPUTS = 5

defworker(rank):
    os.environ['MASTER_ADDR'] = 'localhost'
    os.environ['MASTER_PORT'] = '29500'
    dist.init_process_group(BACKEND, rank=rank, world_size=WORLD_SIZE)

    model = DDP(torch.nn.Linear(1, 1).to(rank), device_ids=[rank])
    # Rank 1 gets one more input than rank 0
    inputs = [torch.tensor([1]).float() for _ in range(NUM_INPUTS + rank)]

    num_inputs = 0
    with Join([model]):
        for input in inputs:
            num_inputs += 1
            loss = model(input).sum()
            loss.backward()

    print(f"Rank {rank} has exhausted all {num_inputs} of its inputs!")

defmain():
    mp.spawn(worker, nprocs=WORLD_SIZE, join=True)

if __name__ == "__main__":
    main()

这将产生以下输出(其中来自 rank 0 和 rank 1 的 print() 语句的顺序可能是任意的):

Rank 0 has exhausted all 5 of its inputs!
Rank 1 has exhausted all 6 of its inputs!

DistributedDataParallel 在引入这个通用的 Join 上下文管理器之前,提供了自己的 join() 上下文管理器。在上面的例子中,使用 with Join([model]): 等同于使用 with model.join():。现有的 DistributedDataParallel.join() 的一个限制是它不允许多个参与类一起使用,例如 DistributedDataParallelZeroRedundancyOptimizer 同时使用。

结合 Join 使用 DistributedDataParallelZeroRedundancyOptimizer

Join 上下文管理器不仅适用于单个类,还可以与多个类一起使用。PyTorch 的 ZeroRedundancyOptimizer 也与该上下文管理器兼容,因此在这里,我们探讨如何修改之前的示例,以同时使用 DistributedDataParallelZeroRedundancyOptimizer

fromtorch.distributed.optimimport ZeroRedundancyOptimizer as ZeRO
fromtorch.optimimport Adam

defworker(rank):
    os.environ['MASTER_ADDR'] = 'localhost'
    os.environ['MASTER_PORT'] = '29500'
    dist.init_process_group(BACKEND, rank=rank, world_size=WORLD_SIZE)

    model = DDP(torch.nn.Linear(1, 1).to(rank), device_ids=[rank])
    optim = ZeRO(model.parameters(), Adam, lr=0.01)
    # Rank 1 gets one more input than rank 0
    inputs = [torch.tensor([1]).float() for _ in range(NUM_INPUTS + rank)]

    num_inputs = 0
    # Pass both `model` and `optim` into `Join()`
    with Join([model, optim]):
        for input in inputs:
            num_inputs += 1
            loss = model(input).sum()
            loss.backward()
            optim.step()

    print(f"Rank {rank} has exhausted all {num_inputs} of its inputs!")

这将产生与之前相同的输出。显著的改变是额外将 ZeroRedundancyOptimizer 实例传递到 Join() 中。

传递关键字参数

类可以在运行时提供关键字参数,以在上下文管理器中修改它们的行为。例如,DistributedDataParallel 提供了一个参数 divide_by_initial_world_size,它决定梯度是否除以初始世界大小或有效世界大小(即未加入的进程数)。这些关键字参数可以直接传递给上下文管理器。

with Join([model, optim], divide_by_initial_world_size=False):
    for input in inputs:
        ...

传递给上下文管理器的关键字参数在所有参与的类之间共享。这不应被视为一种限制,因为我们并不期望多个 Joinable 实例需要相同参数的不同设置。尽管如此,这一点仍需牢记。

Join 是如何工作的?

我们已经初步了解了如何使用 Join 上下文管理器,现在让我们更深入地探讨它的工作原理。这将帮助您更好地理解它所提供的全部功能,并为您准备自定义兼容类打下基础。接下来,我们将详细讲解 Join 类,以及辅助类 JoinableJoinHook

Joinable

首先,与 Join 上下文管理器兼容的类必须继承自抽象基类 Joinable。具体来说,Joinable 必须实现以下内容:

  • join_hook(self, **kwargs) -> JoinHook

这将返回 JoinableJoinHook 实例,用于确定加入的进程应如何影子化 Joinable 执行的每次迭代的集体通信。

  • join_device(self) -> torch.device

这将返回一个设备,供 Join 上下文管理器使用,以执行集体通信,例如 torch.device("cuda:0")torch.device("cpu")

  • join_process_group(self) -> ProcessGroup

这将返回用于 Join 上下文管理器执行集体通信的进程组。

特别是,join_devicejoin_process_group 是必需的属性,以确保上下文管理器能够在已加入和未加入的进程之间调度集体通信。一种用法是使用 all-reduce 在每次迭代时计算未加入进程的数量。另一种用法是实现 throw_on_early_termination=True 所需的机制,我们将在后面详细解释。

DistributedDataParallelZeroRedundancyOptimizer 已经继承了 Joinable 并实现了上述方法,这就是为什么我们可以在前面的示例中直接使用它们。

Joinable 类应确保调用 Joinable 构造函数,因为它初始化了一个 JoinConfig 实例,该实例由上下文管理器内部使用以确保正确性。这将在每个 Joinable 中保存为 _join_config 字段。

JoinHook

接下来,让我们分解一下 JoinHook 类。JoinHook 提供了进入上下文管理器的两个入口点:

  • main_hook(self) -> None

当存在尚未加入的进程时,每个已加入的进程会重复调用此钩子。它的目的是在每次训练迭代中(例如,在一次前向传播、反向传播和优化器步骤中)对 Joinable 执行的集体通信进行影子操作。

  • post_hook(self, is_last_joiner: bool) -> None

在所有进程都加入后,此钩子会被调用。它接收一个额外的 bool 类型参数 is_last_joiner,该参数指示当前进程是否是最后加入的之一。这个参数可能对同步操作很有用。

为了更具体地说明这些钩子的用途,提供的 ZeroRedundancyOptimizer 主钩子会像平常一样执行优化器步骤,因为加入的进程仍然负责更新和同步其参数分片。而提供的 DistributedDataParallel 后置钩子则从最后一个加入的进程之一广播最终更新后的模型,以确保所有进程上的模型保持一致。

Join

最后,让我们来看看这些如何融入Join类本身。

  • __init__(self, joinables: List[Joinable], enable: bool = True, throw_on_early_termination: bool = False)

正如我们在前面的示例中所看到的,构造函数接收参与训练循环的 Joinable 列表。这些应该是每次迭代中执行集体通信的类。

enable 是一个 bool 值,如果您知道不会有输入不均衡的情况,可以将其设置为 False,在这种情况下,上下文管理器将变得类似于 contextlib.nullcontext() 的空操作。这也可能会禁用参与 Joinable 中与 join 相关的计算。

throw_on_early_termination 是一个 bool 值,可以设置为 True,以便在检测到输入不均衡时,每个 rank 立即抛出异常。这对于不符合上下文管理器要求的情况非常有用,通常是在使用不同类别的集体通信时,这些通信可能会任意交错,例如在使用 DistributedDataParallel 时,模型中包含 SyncBatchNorm 层。在这种情况下,应将此参数设置为 True,以便应用程序逻辑可以捕获异常并确定如何处理。

  • 核心逻辑发生在 __exit__() 方法中,该方法会在存在未加入的 rank 时循环,调用每个 Joinable 的主钩子,然后在所有 rank 都加入后,调用它们的后置钩子。主钩子和后置钩子都会按照 Joinable 传入的顺序进行迭代。

  • 上下文管理器需要从未加入的进程获取心跳信号。因此,每个 Joinable 类在其每次迭代的集体通信之前应调用 Join.notify_join_context()。上下文管理器将确保只有第一个传入的 Joinable 实际发送心跳信号。

如上文所述,关于 throw_on_early_terminationJoin 上下文管理器与某些类的组合不兼容。JoinableJoinHook 必须是可序列化的,因为每个钩子在继续下一个之前都会完全执行。换句话说,两个钩子不能重叠。此外,目前主钩子和后钩子都是按照相同的确定性顺序进行迭代的。如果这似乎是一个主要限制,我们可能会修改 API 以允许自定义顺序。

使玩具类与 Join 配合工作

由于上一节介绍了几个概念,让我们通过一个简单的示例来实践这些概念。在这里,我们将实现一个类,用于统计在某个 rank 加入之前所有 ranks 看到的输入数量。这应该能提供一个基本思路,帮助你使自己的类与 Join 上下文管理器兼容。

具体来说,以下代码让每个 rank 都输出:(1) 在它加入之前所有 ranks 看到的输入数量,以及 (2) 所有 ranks 的总输入数量。

importos
importtorch
importtorch.distributedasdist
importtorch.multiprocessingasmp
fromtorch.distributed.algorithms.joinimport Join, Joinable, JoinHook

BACKEND = "nccl"
WORLD_SIZE = 2
NUM_INPUTS = 5

classCounterJoinHook(JoinHook):
r"""
    Join hook for :class:`Counter`.

    Arguments:
        counter (Counter): the :class:`Counter` object using this hook.
        sync_max_count (bool): whether to sync the max count once all ranks
            join.
    """
    def__init__(
        self,
        counter,
        sync_max_count
    ):
        self.counter = counter
        self.sync_max_count = sync_max_count

    defmain_hook(self):
r"""
        Shadows the counter's all-reduce by all-reducing a dim-1 zero tensor.
        """
        t = torch.zeros(1, device=self.counter.device)
        dist.all_reduce(t)

    defpost_hook(self, is_last_joiner: bool):
r"""
        Synchronizes the max count across all :class:`Counter` s if
        ``sync_max_count=True``.
        """
        if not self.sync_max_count:
            return
        rank = dist.get_rank(self.counter.process_group)
        common_rank = self.counter.find_common_rank(rank, is_last_joiner)
        if rank == common_rank:
            self.counter.max_count = self.counter.count.detach().clone()
        dist.broadcast(self.counter.max_count, src=common_rank)

classCounter(Joinable):
r"""
    Example :class:`Joinable` that counts the number of training iterations
    that it participates in.
    """
    def__init__(self, device, process_group):
        super(Counter, self).__init__()
        self.device = device
        self.process_group = process_group
        self.count = torch.tensor([0], device=device).float()
        self.max_count = torch.tensor([0], device=device).float()

    def__call__(self):
r"""
        Counts the number of inputs processed on this iteration by all ranks
        by all-reducing a dim-1 one tensor; increments its own internal count.
        """
        Join.notify_join_context(self)
        t = torch.ones(1, device=self.device).float()
        dist.all_reduce(t)
        self.count += t

    defjoin_hook(self, **kwargs) -> JoinHook:
r"""
        Return a join hook that shadows the all-reduce in :meth:`__call__`.

        This join hook supports the following keyword arguments:
            sync_max_count (bool, optional): whether to synchronize the maximum
                count across all ranks once all ranks join; default is ``False``.
        """
        sync_max_count = kwargs.get("sync_max_count", False)
        return CounterJoinHook(self, sync_max_count)

    @property
    defjoin_device(self) -> torch.device:
        return self.device

    @property
    defjoin_process_group(self):
        return self.process_group

    deffind_common_rank(self, rank, to_consider):
r"""
        Returns the max rank of the ones to consider over the process group.
        """
        common_rank = torch.tensor([rank if to_consider else -1], device=self.device)
        dist.all_reduce(common_rank, op=dist.ReduceOp.MAX, group=self.process_group)
        common_rank = common_rank.item()
        return common_rank

defworker(rank):
    assert torch.cuda.device_count() >= WORLD_SIZE
    os.environ['MASTER_ADDR'] = 'localhost'
    os.environ['MASTER_PORT'] = '29500'
    dist.init_process_group(BACKEND, rank=rank, world_size=WORLD_SIZE)

    counter = Counter(torch.device(f"cuda:{rank}"), dist.group.WORLD)
    inputs = [torch.tensor([1]).float() for _ in range(NUM_INPUTS + rank)]

    with Join([counter], sync_max_count=True):
        for _ in inputs:
            counter()

    print(f"{int(counter.count.item())} inputs processed before rank {rank} joined!")
    print(f"{int(counter.max_count.item())} inputs processed across all ranks!")

defmain():
    mp.spawn(worker, nprocs=WORLD_SIZE, join=True)

if __name__ == "__main__":
    main()

由于 rank 0 接收 5 个输入,而 rank 1 接收 6 个输入,因此生成以下输出:

10 inputs processed before rank 0 joined!
11 inputs processed across all ranks!
11 inputs processed before rank 1 joined!
11 inputs processed across all ranks!

需要强调的关键点:

  • Counter 实例在每次迭代中执行一次全局归约操作,因此主钩子函数也会执行一次全局归约以与其保持一致。

  • Counter 类在其 __call__() 方法的开头调用 Join.notify_join_context(),因为这是在每次迭代的集体通信(即全局归约)之前的位置。

  • is_last_joiner 参数用于在后置钩子中确定广播的源。

  • 我们将 sync_max_count 关键字参数传递给上下文管理器,然后该参数会被转发到 Counter 的加入钩子中。

本页目录