# 작업 실행 및 지연

일반적인 스크립트를 실행하면 명령이 순서대로 실행됩니다. Accelerate를 사용하여 스크립트를 여러 GPU에서 동시에 배포하면 복잡성이 생깁니다. 각 프로세스는 모든 명령을 순서대로 실행하지만, 일부 프로세스가 다른 프로세스보다 빠를 수 있기 때문입니다.

주어진 명령을 실행하기 전에 모든 프로세스가 특정 지점에 도달했는지 기다려야 할 수 있습니다. 예를 들어, 모든 프로세스가 학습을 완료했는지 확인하기 전에 모델을 저장해서는 안 되며, 모든 모델 가중치가 로드되기 전에 학습을 계속해서는 안 됩니다. 이를 위해 다음 줄을 코드에 작성하면 됩니다:

```
accelerator.wait_for_everyone()
```

이 명령은 다른 모든 프로세스가 해당 지점에 도달할 때까지 먼저 도착한 모든 프로세스를 차단합니다(스크립트를 GPU 또는 CPU 하나만 사용하여 실행하는 경우 이 명령은 아무 효과도 없습니다).

이 유틸리티를 사용할 수 있는 몇 가지 예시 사례는 다음과 같습니다:

    Some of these are utilized with the [main_process_first()](/docs/accelerate/main/ko/package_reference/accelerator#accelerate.Accelerator.main_process_first) context manager, which utilizes [wait_for_everyone()](/docs/accelerate/main/ko/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"],
    )
```

## Early Stopping와 같은 체크 적용

특정 프로세스에 의해 설정된 플래그와 함께 작동하는 체크를 수행하려면 `set_trigger` 및 `check_trigger` API를 사용해야 합니다. 이를 수행하는 데 유용한 예로는 조기 종료(early stopping)를 사용하거나 손실을 모니터링하는 상황이 포함될 수 있습니다(각 손실은 프로세스마다 약간씩 다르기 때문).

조건이 충족되면 [Accelerator.set_trigger()](/docs/accelerate/main/ko/package_reference/accelerator#accelerate.Accelerator.set_trigger)를 호출하고, 어떤 프로세스에서든 해당 조건이 충족되었는지 확인하려면 [Accelerator.check_trigger()](/docs/accelerate/main/ko/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
```

