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.16.0).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

执行和延迟任务

当你运行常规脚本时,指令会按顺序执行。使用 Accelerate 将脚本同时部署到多个 GPU 上会引入一个复杂情况:虽然每个进程都会按顺序执行所有指令,但有些进程可能比其他进程更快。

您可能需要等待所有进程到达某个特定点,然后再执行特定指令。例如,在确认所有进程都已完成训练之前,您不应保存模型;同样,在所有模型权重加载完成之前,您也不应继续训练。要实现这一点,只需在代码中写入以下一行:

accelerator.wait_for_everyone()

该指令会阻塞所有最先到达的进程,直到其他所有进程都到达该点(如果仅在单个 GPU 或 CPU 上运行脚本,则此操作不会产生任何效果)。

以下是使用此实用工具的一些示例场景:

Some of these are utilized with the main_process_first() context manager, which utilizes wait_for_everyone() to run a particular set of code on the main process beforehand before triggering and launching the other processes

下载数据集

下载数据集时,应先在主进程中下载,然后再加载缓存的数据集

load_dataset 在底层会执行加锁操作,以防止同时发生多次下载。但如果您下载的内容并非通过此库进行,则应使用此方法。

with accelerator.main_process_first():
    datasets = load_dataset("glue", "mrpc")

在底层,这与调用以下内容相同:

# First do something on the main process
if accelerator.is_main_process:
    datasets = load_dataset("glue", "mrpc")
else:
    accelerator.wait_for_everyone()

# And then send it to the rest of them
if not accelerator.is_main_process:
    datasets = load_dataset("glue", "mrpc")
else:
    accelerator.wait_for_everyone()

保存 state_dict

在保存模型的 state_dict 时,由于通常只在主进程上保存一个文件,因此应指定如下:

if accelerator.is_main_process:
    model = accelerator.unwrap_model(model)
    torch.save(model.state_dict(), "weights.pth")

加载 state_dict

在将 state_dict 加载到模型、优化器或调度器时,您应等待所有工作进程完成权重加载,然后再继续训练

with accelerator.main_process_first():
    state = torch.load("weights.pth")
    model.load_state_dict(state)

应用多工作进程 CPU 操作

在多个工作进程上应用 map() 操作(例如分词)时,应先在主进程中执行,然后再传播到每个工作进程。

datasets = load_dataset("glue", "mrpc")

with accelerator.main_process_first():
    tokenized_datasets = datasets.map(
        tokenize_function,
        batched=True,
        remove_columns=["idx", "sentence1", "sentence2"],
    )

应用诸如之类的检查

若需要实现由特定进程设置标志的检查,应使用 set_trigger 和 check_trigger API。有用的示例包括使用早停并监控损失(因为每个进程上的损失略有不同)等场景。

当条件满足时调用 Accelerator.set_trigger(),在检查任意进程中该条件是否满足时调用 Accelerator.check_trigger():

for (x,y) in data_loader:
    logits = model(x)
    loss = loss_func(logits, y)
    # Assume `should_do_early_stopping` is a custom defined function that returns a conditional
    if should_do_early_stopping(loss):
        accelerator.set_trigger()

    # Later in the training script when we need to check for the breakpoint
    if accelerator.check_trigger():
        break
Update on GitHub