본문 바로가기
딥러닝

Colab 에서 cuda error: device-side assert triggered 등 CUDA error 해결 (huggingface 관련)

by Tiabet 2023. 9. 30.

이번 포스팅도 에러 관련 짧은 포스팅이 될 것이다.

 

나는 딥러닝을 코랩에서만 돌리기 때문에 코랩에서의 오류라고 정리했지만, 구글링을 해보면 로컬 gpu를 사용하시는 분들도 이런 오류를 겪으신 분들이 많은 것 같다.

나는 trainer API에서 train을 사용할 때 오류가 발생했는데, 또 신기한 게 실행할 때마다 미세하게 다른 오류가 발생했다.

 

발생한 오류들은 다음과 같다.

CUDA error: device-side assert triggered
CUBLAS_STATUS_NOT_INITIALIZED Error

대충 이런 식의 Runtime Error 였는데, 워낙 많은 이유로 에러가 발생하다보니 사람마다 말하는 해결법도 아주 다양했다. 하지만 여러 깃헙과 사이트들을 뒤져본 결과 대략적인 가닥을 잡을 수 있었다. 바로 label과 input의 길이가 달라서 발생하는 오류라는 것이었다.

 

처음엔 도통 이게 뭔소린가 싶어서 len 함수로 label, input 길이를 확인해봤지만 분명이 같았다. 하지만 그 길이를 의미하는게 아니라 바로 tokenizer의 단어 길이와 model의 토큰 임베딩의 길이를 의미하는 것이었다.

 

https://saturncloud.io/blog/what-does-runtimeerror-cuda-error-deviceside-assert-triggered-in-pytorch-mean/

 

What Does 'RuntimeError: CUDA Error: Device-Side Assert Triggered' in PyTorch Mean? | Saturn Cloud Blog

As a data scientist or software engineer working with PyTorch, you might have encountered the error message 'RuntimeError: CUDA error: device-side assert triggered' when running your code. This error message can be puzzling, especially if you are not famil

saturncloud.io

오류 해결에 참고했던 글이다. 새턴 클라우드라는 데이터 사이언스와 AI 관련 기업에서 작성한 글 같다.

 

그래서 나같은 경우엔 왜 오류가 발생했냐면, 파인튜닝을 진행할 때 토크나이저에 스페셜 토큰들을 추가해놓고, 모델에는 추가된 토큰을 알려주지 않아서 그런 것이었다.

 

model_checkpoint = "skt/kogpt2-base-v2"

tokenizer = PreTrainedTokenizerFast.from_pretrained(model_checkpoint, bos_token='<bos>', eos_token='<eos>', unk_token='<unk>',
  pad_token='<pad>', mask_token='<mask>', sep_token = '<sep>', padding_side='left')

이렇게 special token들을 tokenizer를 통해 추가적으로 불러오면, 토크나이저가 인식하는 토큰의 개수가 늘어난다. 이를 토크나이저의 사전의 길이가 길어진다고도 볼 수 있다. (special token들을 추가하는 방법은 위와 같은 방식 말고도 많다. ex) add_special_tokens) 

 

하지만 같은 체크포인트에서 모델을 불러와서 그대로 사용한다면, model의 토크나이저의 사전의 길이는 tokenizer를 통해 불러온 special tokens가 포함되어 있지 않기 때문에 토크나이저의 사전의 길이보다 짧을 수밖에 없다. 이러한 불균형이 바로 CUDA Error의 원인이었던 것이다.

 

# Load the existing model checkpoint
model_config = GPT2Config.from_pretrained(model_checkpoint)

# Add the new special token to the model's config
model_config.bos_token_id = tokenizer.bos_token_id
model_config.eos_token_id = tokenizer.eos_token_id
model_config.unk_token_id = tokenizer.unk_token_id
model_config.pad_token_id = tokenizer.pad_token_id
model_config.mask_token_id = tokenizer.mask_token_id
model_config.sep_token_id = tokenizer.sep_token_id  # Add this line

# Initialize the model with the updated configuration
model = GPT2LMHeadModel.from_pretrained(model_checkpoint, config=model_config)

model.resize_token_embeddings(len(tokenizer))

그래서 이러한 식으로 config를 직접 수정해준 다음에 모델을 사용해주어야 하는 것이었다. 

 

 

이번 경우엔 이런 식으로 오류를 해결할 수 있었지만, 대부분의 CUDA Error는 Input Data에 이상이 있는 경우가 허다하다고 한다. (Out of memory 오류는 단순히 메모리 부족 때문에 발생하므로 이 경우와는 다르다.) Input Data에 이상이 있다고 함은, 데이터에 Inf나 Nan 값들이 있거나, input_data와 label의 개수 혹은 길이가 padding이 되어 있지 않아 다르거나 하는 아주 다양한 이유가 다 포함된다. 따라서 이 오류가 발생한다면 혼신의 힘을 다해 구글링을 하는 것이 권장되는 듯 싶다.

 

한 줄 요약 : special token을 사용할 때엔 model을 그냥 불러오지 말고 config를 업데이트하자