Accelerate documentation

执行过程

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v1.15.0).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

执行过程

在使用分布式训练系统时,管理进程在 GPU 上的执行方式和时机至关重要。部分进程比其他进程完成得更快,而某些进程在其他进程尚未完成时不应开始执行。Accelerate 提供了用于编排进程执行时机的工具,以确保所有设备之间保持同步。

本教程将教你如何仅在单台机器上执行进程,以及如何延迟执行,直到所有进程都到达某个特定点。

在单个进程上执行

某些代码只需在特定机器上运行一次,例如打印日志语句,或仅在本地主进程中显示一个进度条。

语句
函数

应使用 accelerator.is_local_main_process 来指示仅应执行一次的代码。

from tqdm.auto import tqdm

progress_bar = tqdm(range(args.max_train_steps), disable=not accelerator.is_local_main_process)

您也可以使用 accelerator.is_local_main_process 来包裹一条语句。

对于未包裹在 accelerator.is_local_main_process 中的独立 print 语句,请将 print 替换为 Accelerate 的 print() 方法,以便每个进程仅打印一次。

if accelerator.is_local_main_process:
    print("Accelerate is the best")

您也可以指示 Accelerate 在所有进程上仅执行一次代码,而不管机器数量如何。当您向 Hub 上传最终模型时,这非常有用。

statement
函数

应使用 accelerator.is_main_process 来标记那些在所有进程中只需执行一次的代码。

if accelerator.is_main_process:
    repo.push_to_hub()

在特定进程上执行

Accelerate 还可以帮助你在特定进程或本地进程索引上执行函数。

特定进程
本地进程

使用 on_process() 方法并指定进程索引,以在特定进程上执行函数。

@accelerator.on_process(process_index=0)
def do_my_thing():
    "Something done on process index 0"
    do_thing_on_index_zero()

延迟执行

当您在多个 GPU 上同时运行脚本时,部分代码的执行速度可能快于其他部分。您可能需要等待所有进程到达某个特定点,然后再执行下一组指令。例如,在确认所有进程都已完成训练之前,您不应保存模型。

为此,请在代码中添加 wait_for_everyone()。这会阻止所有先完成处理的进程继续执行,直到所有剩余进程都到达同一位置(如果在单 GPU 或 CPU 上运行,则此操作无效)。

accelerator.wait_for_everyone()
Update on GitHub