# 执行和延迟任务

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

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

```
accelerator.wait_for_everyone()
```

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

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

    Some of these are utilized with the [main_process_first()](/docs/accelerate/v1.16.0/zh/package_reference/accelerator#accelerate.Accelerator.main_process_first) context manager, which utilizes [wait_for_everyone()](/docs/accelerate/v1.16.0/zh/package_reference/accelerator#accelerate.Accelerator.wait_for_everyone) to run a particular set of code on the main process beforehand before triggering and launching the other processes

## 下载数据集 

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

    `load_dataset` 会在底层执行加锁操作，以防止同时发生多次下载。但如果您未使用此库进行下载，则应使用此方法。
    

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

在底层，这与调用以下内容相同：

```python
# 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` 时，由于通常只在主进程上保存一个文件，因此应指定如下：

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

## 加载 `state_dict`

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

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

## 应用多工作进程 CPU 操作 

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

```python
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()](/docs/accelerate/v1.16.0/zh/package_reference/accelerator#accelerate.Accelerator.set_trigger)，在检查任意进程中该条件是否满足时调用 [Accelerator.check_trigger()](/docs/accelerate/v1.16.0/zh/package_reference/accelerator#accelerate.Accelerator.check_trigger)：

```python
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
```

