# 디버깅

분산 학습 문제를 디버깅하는 작업은 일반적으로 수치 문제, 통신 실패, 런타임 오류, 빌드 오류 중 한 가지 범주로 나뉩니다.

## Underflow and overflow detection

Underflow와 overflow는 activations 또는 weights가 `inf` 또는 `nan`에 도달하거나, `loss=NaN`인 경우 발생합니다. 이를 감지하려면 `TrainingArguments.debug()`에서 `DebugUnderflowOverflow` 모듈을 활성화하거나, 이를 import하여 자체 학습 루프에 추가하세요.

```py
from transformers import TrainingArguments

args = TrainingArguments(
    debug="underflow_overflow",
    ...
)
```

```py
from transformers.debug_utils import DebugUnderflowOverflow

debug_overflow = DebugUnderflowOverflow(model)
```

[DebugUnderflowOverflow](/docs/transformers/v5.24.1/ko/internal/trainer_utils#transformers.debug_utils.DebugUnderflowOverflow)은 각 forward 호출 후 입력 및 출력 변수와 해당 모델 가중치를 검사하기 위해 모델에 훅을 삽입합니다. 활성화 값 또는 가중치의 요소 중 하나 이상에서 `inf` 또는 `nan`이 감지되면, 해당 모듈은 아래와 같은 보고서를 출력합니다.

아래 예시는 [google/mt5-small](https://huggingface.co/google/mt5-small)을 사용한 fp16 혼합 정밀도 학습입니다.

```shell
Detected inf/nan during batch_number=0
Last 21 forward frames:
abs min  abs max  metadata
                  encoder.block.1.layer.1.DenseReluDense.dropout Dropout
0.00e+00 2.57e+02 input[0]
0.00e+00 2.85e+02 output
[...]
                  encoder.block.2.layer.0 T5LayerSelfAttention
6.78e-04 3.15e+03 input[0]
2.65e-04 3.42e+03 output[0]
             None output[1]
2.25e-01 1.00e+04 output[2]
                  encoder.block.2.layer.1.layer_norm T5LayerNorm
8.69e-02 4.18e-01 weight
2.65e-04 3.42e+03 input[0]
1.79e-06 4.65e+00 output
                  encoder.block.2.layer.1.DenseReluDense.wi_0 Linear
2.17e-07 4.50e+00 weight
1.79e-06 4.65e+00 input[0]
2.68e-06 3.70e+01 output
                  encoder.block.2.layer.1.DenseReluDense.wi_1 Linear
8.08e-07 2.66e+01 weight
1.79e-06 4.65e+00 input[0]
1.27e-04 2.37e+02 output
                  encoder.block.2.layer.1.DenseReluDense.dropout Dropout
0.00e+00 8.76e+03 input[0]
0.00e+00 9.74e+03 output
                  encoder.block.2.layer.1.DenseReluDense.wo Linear
1.01e-06 6.44e+00 weight
0.00e+00 9.74e+03 input[0]
3.18e-04 6.27e+04 output
                  encoder.block.2.layer.1.DenseReluDense T5DenseGatedGeluDense
1.79e-06 4.65e+00 input[0]
3.18e-04 6.27e+04 output
                  encoder.block.2.layer.1.dropout Dropout
3.18e-04 6.27e+04 input[0]
0.00e+00      inf output
```

첫 번째 줄은 오류가 발생한 배치 번호를 표시합니다. 이 경우, 오류는 배치 0에서 발생했습니다.

각 프레임은 보고 대상 모듈을 설명합니다. 예를 들어, 아래 프레임은 인코더의 두 번째 블록의 첫 번째 레이어에 있는 layer norm인 `encoder.block.2.layer.1.layer_norm`에 대해 보고합니다. forward 호출은 `T5LayerNorm`에 대한 것입니다.

```shell
                  encoder.block.2.layer.1.layer_norm T5LayerNorm
8.69e-02 4.18e-01 weight
2.65e-04 3.42e+03 input[0]
1.79e-06 4.65e+00 output
```

마지막 프레임은 `DenseReluDense` 클래스 내부의 `dropout` 속성을 호출하는 `Dropout.forward` 함수에 대한 보고서를 제공합니다. 오버플로(`inf`)는 인코더의 두 번째 블록에서 첫 번째 배치에서 발생했습니다. 가장 큰 입력 요소는 6.27e+04였습니다.

```shell
                  encoder.block.2.layer.1.DenseReluDense T5DenseGatedGeluDense
1.79e-06 4.65e+00 input[0]
3.18e-04 6.27e+04 output
                  encoder.block.2.layer.1.dropout Dropout
3.18e-04 6.27e+04 input[0]
0.00e+00      inf output
```

`T5DenseGatedGeluDense.forward` 출력 활성화 값의 최대치가 6.27e+04로, fp16의 최대치인 6.4e+04에 근접했습니다. 다음 단계에서 `Dropout`은 일부 요소를 0으로 만든 후 가중치를 재정규화하여 최대치를 6.4e+04 이상으로 끌어올리고, 이로 인해 오버플로가 발생합니다.

이제 오류가 발생하는 위치를 알게 되었으므로 [modeling_t5.py](https://github.com/huggingface/transformers/blob/main/src/transformers/models/t5/modeling_t5.py)의 모델링 코드를 조사해 보세요.

```py
class T5DenseGatedGeluDense(nn.Module):
    def __init__(self, config):
        super().__init__()
        self.wi_0 = nn.Linear(config.d_model, config.d_ff, bias=False)
        self.wi_1 = nn.Linear(config.d_model, config.d_ff, bias=False)
        self.wo = nn.Linear(config.d_ff, config.d_model, bias=False)
        self.dropout = nn.Dropout(config.dropout_rate)
        self.gelu_act = ACT2FN["gelu_new"]

    def forward(self, hidden_states):
        hidden_gelu = self.gelu_act(self.wi_0(hidden_states))
        hidden_linear = self.wi_1(hidden_states)
        hidden_states = hidden_gelu * hidden_linear
        hidden_states = self.dropout(hidden_states)
        hidden_states = self.wo(hidden_states)
        return hidden_states
```

해결 방법 중 하나는 값이 너무 커지기 몇 단계 전에 fp32로 전환하는 것입니다. 이렇게 하면 곱셈이나 합산 시 숫자가 오버플로되지 않습니다. 다른 옵션으로는 혼합 정밀도 학습(`amp`)을 일시적으로 비활성화하는 것이 있습니다.

```py
import torch

def forward(self, hidden_states):
    device_type = hidden_states.device.type
    if torch.is_autocast_enabled(device_type):
        with torch.amp.autocast(device_type, enabled=False):
            return self._forward(hidden_states)
    else:
        return self._forward(hidden_states)
```

이 보고서는 전체 프레임의 입력과 출력만 다룹니다. `forward` 함수 내부의 중간 값을 분석하려면, 각 forward 호출 뒤에 `detect_overflow`를 추가하여 `forwarded_states`의 `inf` 또는 `nan`을 추적하세요.

```py
from transformers.debug_utils import detect_overflow

class T5LayerFF(nn.Module):
    [...]

    def forward(self, hidden_states):
        forwarded_states = self.layer_norm(hidden_states)
        detect_overflow(forwarded_states, "after layer_norm")
        forwarded_states = self.DenseReluDense(forwarded_states)
        detect_overflow(forwarded_states, "after DenseReluDense")
        return hidden_states + self.dropout(forwarded_states)
```

[DebugUnderflowOverflow](/docs/transformers/v5.24.1/ko/internal/trainer_utils#transformers.debug_utils.DebugUnderflowOverflow)가 출력하는 프레임 수를 설정합니다.

```py
from transformers.debug_utils import DebugUnderflowOverflow

debug_overflow = DebugUnderflowOverflow(model, max_frames_to_save=100)
```

### 배치 트레이싱

[DebugUnderflowOverflow](/docs/transformers/v5.24.1/ko/internal/trainer_utils#transformers.debug_utils.DebugUnderflowOverflow)은 underflow 및 overflow 감지를 비활성화한 상태로 각 배치의 절대 최소값과 최대값을 추적할 수도 있습니다. 이를 통해 모델에서 값이 발산하기 시작하는 위치를 파악하는 데 도움이 됩니다.

아래 예제는 배치 1과 3을 추적합니다(배치는 0부터 인덱싱됩니다).

```py
debug_overflow = DebugUnderflowOverflow(model, trace_batch_nums=[1, 3])
```

```shell
                  *** Starting batch number=1 ***
abs min  abs max  metadata
                  shared Embedding
1.01e-06 7.92e+02 weight
0.00e+00 2.47e+04 input[0]
5.36e-05 7.92e+02 output
[...]
                  decoder.dropout Dropout
1.60e-07 2.27e+01 input[0]
0.00e+00 2.52e+01 output
                  decoder T5Stack
     not a tensor output
                  lm_head Linear
1.01e-06 7.92e+02 weight
0.00e+00 1.11e+00 input[0]
6.06e-02 8.39e+01 output
                   T5ForConditionalGeneration
     not a tensor output

                  *** Starting batch number=3 ***
abs min  abs max  metadata
                  shared Embedding
1.01e-06 7.92e+02 weight
0.00e+00 2.78e+04 input[0]
5.36e-05 7.92e+02 output
[...]
```

[DebugUnderflowOverflow](/docs/transformers/v5.24.1/ko/internal/trainer_utils#transformers.debug_utils.DebugUnderflowOverflow)은 많은 프레임을 보고하므로 값이 분기되는 위치를 파악하기가 더 쉽습니다. 문제가 배치 150 근처에 있다는 것을 알고 있다면, 숫자가 달라지기 시작하는 위치를 비교하기 위해 트레이스를 배치 149와 150에 집중하세요.

특정 배치 번호, 예를 들어 배치 3 이후에 trace를 중단할 수도 있습니다.

```py
debug_overflow = DebugUnderflowOverflow(model, trace_batch_nums=[1, 3], abort_after_batch_num=3)
```

## 커뮤니케이션

분산 학습은 프로세스 간 및 노드 간 통신을 필요로 하며, 이는 오류의 일반적인 원인입니다.

아래 스크립트를 다운로드하여 네트워크 문제를 진단한 후 실행하여 GPU 통신을 테스트합니다. 아래 명령은 두 개의 GPU를 테스트합니다. 시스템에 맞게 `--nproc_per_node`와 `--nnodes`를 조정하세요.

```bash
wget https://raw.githubusercontent.com/huggingface/transformers/main/scripts/distributed/torch-distributed-gpu-test.py
python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py
```

두 GPU가 성공적으로 통신하고 메모리를 할당하면 스크립트는 `OK`를 출력합니다. 자세한 내용과 SLURM 환경에서 실행하는 방법은 진단 스크립트를 참고하세요.

상세한 NCCL 디버깅 출력을 얻으려면 `NCCL_DEBUG=INFO`를 설정하세요.

```bash
NCCL_DEBUG=INFO python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py
```

## DeepSpeed

오류가 발생하면 먼저 DeepSpeed가 원인이 아닌지 확인하세요. DeepSpeed 없이 설정을 다시 시도해 보시고, 오류가 계속되면 문제를 보고하세요. Transformers 통합과 무관한 문제는 DeepSpeed [저장소](https://github.com/microsoft/DeepSpeed)에서 이슈를 등록하세요.

Transformers 통합과 관련된 이슈의 경우, 다음 정보를 포함하세요.

* 전체 DeepSpeed 구성 파일.
* [Trainer](/docs/transformers/v5.24.1/ko/main_classes/trainer#transformers.Trainer)의 커맨드 라인 인수를 사용하거나, [Trainer](/docs/transformers/v5.24.1/ko/main_classes/trainer#transformers.Trainer) 설정을 직접 스크립트로 작성하는 경우 [TrainingArguments](/docs/transformers/v5.24.1/ko/main_classes/trainer#transformers.TrainingArguments)를 사용하세요(많은 관련 없는 항목을 포함하고 있으므로 [TrainingArguments](/docs/transformers/v5.24.1/ko/main_classes/trainer#transformers.TrainingArguments) 전체를 덤프하지 마세요).
* 이러한 명령어의 출력입니다.

    ```bash
    python -c 'import torch; print(f"torch: {torch.__version__}")'
    python -c 'import transformers; print(f"transformers: {transformers.__version__}")'
    python -c 'import deepspeed; print(f"deepspeed: {deepspeed.__version__}")'
    ```

* 문제를 재현하기 위한 Google Colab 노트북 링크.
* 문제를 재현하기 위한 표준 또는 비커스텀 데이터셋 또는 기존 예제.

### 시작 시 프로세스가 종료되었습니다

DeepSpeed 프로세스가 시작 중 traceback 없이 종료된 경우, 프로그램이 사용 가능하거나 허용된 CPU 메모리보다 더 많은 메모리를 할당하려고 시도한 것입니다. 이 경우 OS 커널은 프로세스를 종료합니다.

`offload_optimizer`, `offload_param` 또는 둘 다 CPU로 오프로드하도록 설정되어 있는지 설정 파일을 확인하세요.

NVMe와 ZeRO-3를 설정한 경우, 대신 NVMe로 오프로딩을 시도해 보세요. 먼저 모델의 메모리 요구 사항을 [추정](https://deepspeed.readthedocs.io/en/latest/memory.html)해 보세요.

### NaN 손실

NaN 손실은 모델이 bf16로 사전 학습된 후 fp16로 사용되는 경우(특히 TPU로 학습된 모델에서 매우 흔함)에 자주 발생합니다. 하드웨어가 지원하는 경우(예: TPU, Ampere GPU 또는 그 이상)에는 fp32 또는 bf16를 사용하세요.

fp16도 오버플로우를 유발할 수 있습니다. 아래와 같은 설정 파일을 사용 중이라면 로그에서 오버플로우 오류를 확인할 수 있습니다.

```json
{
    "fp16": {
        "enabled": "auto",
        "loss_scale": 0,
        "loss_scale_window": 1000,
        "initial_scale_power": 16,
        "hysteresis": 2,
        "min_loss_scale": 1
    }
}
```

아래의 `OVERFLOW!` 오류는 DeepSpeed loss scaler가 loss overflow를 극복할 수 있는 scaling 계수를 찾지 못했음을 의미합니다. 더 높은 `initial_scale_power` 값(보통 32가 작동합니다)을 사용해 보세요.

```bash
0%|                                                                                                                             | 0/189 [00:00<?, ?it/s]
 [deepscale] OVERFLOW! Rank 0 Skipping step. Attempted loss scale: 262144, reducing to 262144
  1%|▌                                                                                                                    | 1/189 [00:00<01:26,  2.17it/s]
 [deepscale] OVERFLOW! Rank 0 Skipping step. Attempted loss scale: 262144, reducing to 131072.0
  1%|█▏
 [...]
 [deepscale] OVERFLOW! Rank 0 Skipping step. Attempted loss scale: 1, reducing to 1
 14%|████████████████▌                                                                                                   | 27/189 [00:14<01:13,  2.21it/s]
 [deepscale] OVERFLOW! Rank 0 Skipping step. Attempted loss scale: 1, reducing to 1
 15%|█████████████████▏                                                                                                  | 28/189 [00:14<01:13,  2.18it/s]
 [deepscale] OVERFLOW! Rank 0 Skipping step. Attempted loss scale: 1, reducing to 1
 15%|█████████████████▊                                                                                                  | 29/189 [00:15<01:13,  2.18it/s]
 [deepscale] OVERFLOW! Rank 0 Skipping step. Attempted loss scale: 1, reducing to 1
[...]
```

## DeepSpeed CUDA

DeepSpeed는 CUDA C++ 코드를 컴파일하며, 이는 CUDA가 필요한 PyTorch 확장에서 빌드 오류의 일반적인 원인입니다. 이러한 오류는 시스템에 CUDA가 설치된 방식에 따라 달라집니다.

```bash
pip install deepspeed
```

> [!TIP]
> 기타 설치 관련 문제가 발생하면 DeepSpeed 팀에게 [이슈를 등록](https://github.com/microsoft/DeepSpeed/issues)하세요.

### 동일하지 않은 툴킷

PyTorch에는 자체 CUDA toolkit이 포함되어 있지만, DeepSpeed에는 시스템 전체에 동일한 CUDA 버전이 설치되어 있어야 합니다. Python 환경에서 `cudatoolkit==10.2`로 PyTorch를 설치했다면, 시스템 전체에 CUDA 10.2도 설치해야 합니다.

정확한 위치는 시스템에 따라 다르지만, Unix 시스템에서 가장 일반적인 경로는 `/usr/local/cuda-10.2`입니다. CUDA가 설치되고 `PATH`에 추가된 후에는 다음 명령으로 설치 위치를 확인하세요.

```bash
which nvcc
```

### 여러 툴킷

시스템에 CUDA 툴킷이 하나 이상 설치되어 있을 수 있습니다.

```text
/usr/local/cuda-10.2
/usr/local/cuda-11.0
```

패키지 설치 프로그램은 일반적으로 마지막에 설치된 버전의 경로를 설정합니다. 빌드가 올바른 CUDA 버전을 찾지 못해 실패하는 경우, `PATH`와 `LD_LIBRARY_PATH`를 올바른 경로로 설정하세요.

먼저 이 환경 변수들을 확인하세요.

```bash
echo $PATH
echo $LD_LIBRARY_PATH
```

`PATH`는 실행 파일의 위치를 나열합니다. `LD_LIBRARY_PATH`는 공유 라이브러리의 위치를 나열합니다. 앞의 항목이 우선하며, `:`로 여러 항목을 구분합니다. 올바른 CUDA 경로를 맨 앞에 추가하여 우선순위를 높입니다.

```bash
# adjust the version and full path if needed
export PATH=/usr/local/cuda-10.2/bin:$PATH
export LD_LIBRARY_PATH=/usr/local/cuda-10.2/lib64:$LD_LIBRARY_PATH
```

할당된 디렉터리가 존재하는지도 확인하세요. `lib64` 하위 디렉터리에는 `libcudart.so`와 같은 CUDA `.so` 객체가 포함되어 있습니다. 실제 파일 이름을 확인하고 그에 맞게 업데이트하세요.

### 이전 버전

구버전 CUDA는 구버전 컴파일러를 요구할 수 있습니다. 예를 들어, CUDA가 `gcc-7`를 요구하지만 시스템에 `gcc-9`만 설치되어 있는 경우 빌드가 실패합니다. 필요한 구버전 컴파일러를 설치하고 CUDA 빌드 시스템이 이를 찾을 수 있도록 심볼릭 링크를 생성하세요.

```bash
# adjust the path to your system
sudo ln -s /usr/bin/gcc-7  /usr/local/cuda-10.2/bin/gcc
sudo ln -s /usr/bin/g++-7  /usr/local/cuda-10.2/bin/g++
```

### Prebuild

DeepSpeed 설치 또는 런타임 빌드 시 여전히 문제가 발생하면, 먼저 DeepSpeed 모듈을 사전 빌드하세요. 로컬 빌드를 위해 아래 명령어를 실행하세요.

```bash
git clone https://github.com/deepspeedai/DeepSpeed/
cd DeepSpeed
rm -rf build
TORCH_CUDA_ARCH_LIST="8.6" DS_BUILD_CPU_ADAM=1 DS_BUILD_UTILS=1 pip install . \
--global-option="build_ext" --global-option="-j8" --no-cache -v \
--disable-pip-version-check 2>&1 | tee build.log
```

> [!TIP]
> NVMe 오프로드를 사용하려면 빌드 명령에 `DS_BUILD_AIO=1`을 추가하세요. libaio-dev 패키지가 시스템 전체에 설치되어 있는지 확인하세요.

다음으로, `TORCH_CUDA_ARCH_LIST`에 GPU 아키텍처를 설정합니다. NVIDIA GPU 전체 목록과 해당 아키텍처는 [CUDA GPUs 페이지](https://developer.nvidia.com/cuda-gpus)에서 확인할 수 있습니다. 아키텍처에 해당하는 PyTorch 버전을 확인하려면 아래 명령을 실행합니다.

```bash
python -c "import torch; print(torch.cuda.get_arch_list())"
```

다음 명령어로 GPU의 아키텍처를 확인합니다.

```bash
CUDA_VISIBLE_DEVICES=0 python -c "import torch; print(torch.cuda.get_device_capability())"
```

GPU `0`의 아키텍처를 확인하려면 다음 명령을 실행하세요. 출력에는 GPU 아키텍처를 함께 구성하는 `major`와 `minor` 값이 표시됩니다. 아래 예시에서는 아키텍처 `8.6`가 표시됩니다.

```bash
CUDA_VISIBLE_DEVICES=0 python -c "import torch; \
print(torch.cuda.get_device_properties(torch.device('cuda')))
"_CudaDeviceProperties(name='GeForce RTX 3090', major=8, minor=6, total_memory=24268MB, multi_processor_count=82)"
```

결과가 `8, 6`인 경우 `TORCH_CUDA_ARCH_LIST="8.6"`을 설정합니다. 서로 다른 아키텍처를 가진 여러 GPU의 경우 `TORCH_CUDA_ARCH_LIST="6.1;8.6"`처럼 나열합니다.

`TORCH_CUDA_ARCH_LIST`를 생략하고 빌드 프로그램이 GPU 아키텍처를 자동으로 감지하도록 할 수 있지만, 이는 대상 머신의 실제 GPU와 일치하지 않을 수 있습니다. 아키텍처를 명시적으로 설정하는 것이 더 신뢰할 수 있습니다.

동일한 설정으로 여러 머신에서 학습하려면 바이너리 휠을 빌드하세요.

```bash
git clone https://github.com/deepspeedai/DeepSpeed/
cd DeepSpeed
rm -rf build
TORCH_CUDA_ARCH_LIST="8.6" DS_BUILD_CPU_ADAM=1 DS_BUILD_UTILS=1 \
python setup.py build_ext -j8 bdist_wheel
```

`dist/deepspeed-0.3.13+8cd046f-cp38-cp38-linux_x86_64.whl`와 같은 바이너리 휠을 생성합니다. 로컬 또는 다른 머신에 설치할 수 있습니다.

```bash
pip install deepspeed-0.3.13+8cd046f-cp38-cp38-linux_x86_64.whl
```

