[Lab] CUDA error: invalid device ordinal 해결하기

츄르츄르츄츄·2024년 8월 15일
0

🚀CUDA error: invalid device ordinal 해결해보자

환경

os: Ubuntu 22.04
gpu: 4 nvidia gpu

상황

  1. nvidia-smi도 gpu 4개가 뜬다.
  2. 아래 명령에서도 gpu 4개가 뜬다.
print("gpu개수 확인: ", torch.cuda.device_count())
  1. 하지만 다음 에러가 발생
RuntimeError: CUDA error: invalid device ordinal CUDA kernel
errors might be asynchronously reported at some other API 
call, so the stacktrace below might be incorrect. For 
debugging consider passing CUDA_LAUNCH_BLOCKING=1 Compile 
with `TORCH_USE_CUDA_DSA` to enable device-side assertions.

🕵해결방법: GPT야 도와줘

🕵방법 1. device_map = "auto"😡

device_map을 auto로 정해서 api가 직접 고르도록하쟈

device_map = "auto"
model = AutoModelForCausalLM.from_pretrained(
        base_model,
        torch_dtype=torch.bfloat16,
        device_map=device_map,
)

근데 이러면 gpu를 한 개만 쓰려는 것 같다.😒

🕵방법 2. 디버깅😚

1. 디버깅을 해보자

import os
os.environ['CUDA_LAUNCH_BLOCKING'] = "1"

위 코드를 코드에 삽입한 뒤 다시 실행하면 구체적인 에러메시지가 나온다.

RuntimeError: CUDA error: invalid device ordinal
Compile with `TORCH_USE_CUDA_DSA` to enable device-side assertions.

2. --nproc_per_node 변경

이거는 연결된 gpu의 개수라고 생각하면 된다.
정확히는 프로세서/노드
만약 GPU를 4개 가지고 있는데, --nproc_per_node=8이면 에러가 발생한다. 수정하자.

--nproc_per_node=4

ps. 상세히 gpu 개수를 파악하려면..

gpu를 상세히 확인하려면 아래 코드를 삽입하고 로그를 보면 된다.

if torch.cuda.is_available():
    print(f"Number of available GPUs: {torch.cuda.device_count()}")
    for i in range(torch.cuda.device_count()):
        print(f"GPU {i}: {torch.cuda.get_device_name(i)}")
else:
    print("CUDA is not available.")
profile
나는야 이빨요정

0개의 댓글