# DDP

[DistributedDataParallel (DDP)](https://docs.pytorch.org/tutorials/beginner/ddp_series_theory.html)은 각 GPU에 모델의 전체 사본을 유지합니다. 각 GPU는 겹치지 않는 데이터 샤드를 전방 및 역방향 패스로 처리합니다. 옵티마이저 단계 전에, 올리듀스(all-reduce)가 모든 GPU에 걸쳐 기울기를 평균화하여 모든 모델 사본이 동일하게 유지되도록 합니다. 모델이 단일 GPU에 맞을 때 DDP를 사용하세요.

```text
                         ┌─────────────────┐
                         │  training data  │
                         └────────┬────────┘
               ┌──────────────────┼──────────────────┐
               │ shard 0          │ shard 1          │ shard 2
               ▼                  ▼                  ▼
        ┌─────────────┐    ┌─────────────┐    ┌─────────────┐
        │   model     │    │   model     │    │   model     │
        │  (copy 0)   │    │  (copy 1)   │    │  (copy 2)   │
        │   GPU 0     │    │   GPU 1     │    │   GPU 2     │
        └──────┬──────┘    └──────┬──────┘    └──────┬──────┘
               │ grads            │ grads            │ grads
               └──────────────────┼──────────────────┘
                               all-reduce
                          (average gradients)
               ┌──────────────────┼──────────────────┐
               ▼                  ▼                  ▼
        ┌─────────────┐    ┌─────────────┐    ┌─────────────┐
        │  optimizer  │    │  optimizer  │    │  optimizer  │
        │    step     │    │    step     │    │    step     │
        └─────────────┘    └─────────────┘    └─────────────┘
          (identical)        (identical)        (identical)
```

멀티프로세스 런처인 [Accelerate](./accelerate)와 같이 실행하면 DDP가 자동으로 활성화됩니다.

```cli
# 4 GPUs on one machine
accelerate launch --num_processes 4 train.py
```

## DDP 구성

DDP 동작을 제어하려면 이 [TrainingArguments](/docs/transformers/v5.23.0/ko/main_classes/trainer#transformers.TrainingArguments)를 전달하세요.

- `gradient_accumulation_steps()`는 all-reduce를 수행하는 시점을 결정합니다. [Trainer](/docs/transformers/v5.23.0/ko/main_classes/trainer#transformers.Trainer)는 중간 누적 단계에서는 all-reduce를 건너뛰고 최종 micro-batch에서만 실행합니다. 예를 들어, `gradient_accumulation_steps=4`인 경우 all-reduce는 4번의 backward pass마다 실행됩니다.
- `~TrainingArguments.ddp_find_unused_parameters`는 forward pass가 끝난 시점에 그래디언트를 받지 않을 파라미터를 autograd 그래프를 탐색하여 찾아내고, all-reduce를 막지 않도록 해당 파라미터를 ready 상태로 표시합니다. `~TrainingArguments.gradient_checkpointing`과 함께 사용하지 마세요. gradient checkpointing은 중간 activations를 폐기하고 필요할 때 다시 계산하기 때문입니다.
- `~TrainingArguments.ddp_bucket_cap_mb`는 backward pass 동안 그래디언트를 단일 all-reduce로 배치하기 위한 버킷 크기입니다. 버킷이 클수록 all-reduce 호출 횟수가 줄어들고 런치 오버헤드가 감소합니다.
- `~TrainingArguments.ddp_broadcast_buffers`는 모든 forward pass 시작 시 rank 0에서 다른 모든 rank로 모델 버퍼(BatchNorm 실행 통계 등)를 동기화합니다. 모델이 LayerNorm만 사용하는 경우 비활성화하세요. `~TrainingArguments.gradient_checkpointing`과 함께 사용하지 마세요.
- `~TrainingArguments.ddp_backend`은 통신 백엔드를 설정합니다. NVIDIA GPU에는 `"nccl"`을(를) 사용하세요(기본값이며 가장 빠름), CPU 학습이나 디버깅에는 `"gloo"`를(를) 사용하고, 기타 하드웨어에는 `"xccl"`, `"hccl"` 또는 `"cncl"`을(를) 사용하세요.
- `ddp_timeout()`은 모든 프로세스와 연산(all-reduce, broadcast)이 완료되는 데 걸리는 시간 한도를 설정합니다. 대형 모델을 느리게 로드하는 경우와 같이 프로세스가 멈추면, 타임아웃이 무한정 차단되는 대신 오류를 발생시킵니다.

```py
from transformers import TrainingArguments

args = TrainingArguments(
    ...,
    gradient_accumulation_steps=4,
    ddp_backend="nccl",
    ddp_find_unused_parameters=False,
    ddp_bucket_cap_mb=25,
    ddp_broadcast_buffers=True,
    ddp_timeout=1800,
)
```

## 다음 단계

- 단일 GPU에 맞지 않을 정도로 큰 모델을 학습하는 경우 [FSDP](./fsdp)를 참조하세요.
- ZeRO 최적화 및 오프로딩에 대해 [DeepSpeed](./deepspeed)를 참조하세요.
- DDP의 작동 방식에 대한 자세한 내용은 The Ultra-Scale Playbook의 [Data Parallelism](https://nanotron-ultrascale-playbook.static.hf.space/index.html#data_parallelism) 장을 참고하세요.

