HuggingFace Basic

Gongsam·2025년 3월 19일
0

project

목록 보기
1/3

1. 발단

그저 허깅페이스에서 딥시크 모델을 발견하고.. 한 번 사용해보고 싶었을 뿐인데

2. 문제

오프로드

The current device_map had weights offloaded to the disk. Please provide an offload_folder for them. Alternatively, make sure you have safetensors installed if the model you are using offers the weights in this format.
모델이 메모리에 전부 로드되지 못하고 일부 가중치가 디스크로 오프로드되었기 때문에 발생

1️⃣ offload_folder 설정하기
DeepSeek 모델이 GPU VRAM을 초과하는 경우, 일부 가중치를 로컬 디스크에 저장하면서 사용해야. 이를 위해 offload_folder를 지정 필요.

from transformers import AutoModelForCausalLM, AutoTokenizer
import torch

# DeepSeek 모델 불러오기
model_name = "deepseek-ai/deepseek-llm-7b-base"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(
    model_name, 
    torch_dtype=torch.float16, 
    device_map="auto",
    offload_folder="./offload"  # 오프로드 폴더 지정
)

print("모델 로드 완료!")

✔ 오프로드 폴더(./offload)를 지정하여 오류 해결
✔ 모델이 VRAM을 초과하면 일부를 디스크에 저장하면서 실행됨

2️⃣ safetensors 설치하기
DeepSeek 모델이 safetensors 포맷을 제공하는 경우, 이 라이브러리를 설치하면 더 효율적으로 모델을 로드할 수 있어.

pip install safetensors

그 후 다시 모델을 불러오면 디스크 오프로드 없이 실행될 수도 있어.

모델은 불러와졌지만 출력이 공백만 됨

max_length와 max_new_tokens 설정

max_length와 max_new_tokens의 조합이 제대로 설정되지 않아서 텍스트가 제대로 생성되지 않았을 가능성 존재
=> max_length 늘리고 max_new_tokens를 새로 설정함

런타임을 GPU가 아닌 CPU에서 생긴 문제

inputs = tokenizer(prompt, return_tensors="pt").to("cuda")  # GPU 사용

이 부분에서

해결 방법

1️⃣ Colab에서 GPU 활성화하기
1. 런타임(Runetime) → 런타임 유형 변경(Change runtime type) 클릭
2. 하드웨어 가속기(Hardware accelerator)를 "GPU"로 변경
3. "저장(Save)" 버튼을 눌러 적용

모델 체크포인트 로드 오류

model = load_checkpoint_and_dispatch(
model,
checkpoint=model_name,
device_map="auto",
offload_folder=offload_folder,
no_split_module_classes=["DeepseekBlock"]
)
  • 에러 메시지
`checkpoint` should be the path to a file containing a whole state dict, or the index of a sharded checkpoint, or a folder containing a sharded checkpoint or the whole state dict, but got deepseek-ai/deepseek-llm-7b-base.
  • load_checkpoint_and_dispatch 함수의 checkpoint 매개변수에 모델 이름 대신 로컬 체크포인트 경로가 필요하기 때문에 발생하는 문제
# 1. 모델 체크포인트 다운로드
model_repo = "deepseek-ai/deepseek-llm-7b-base"
local_dir = "./deepseek-7b-checkpoints"
snapshot_download(repo_id=model_repo, local_dir=local_dir)

# 2. 체크포인트 경로 지정 (중요)
checkpoint_path = local_dir # 샤딩된 체크포인트 인덱스 파일

# 3. 수정된 함수 호출
model = load_checkpoint_and_dispatch(
    model,
    checkpoint=checkpoint_path,  # 모델 이름 대신 경로 사용
    device_map="auto",
    offload_folder=offload_folder,
    no_split_module_classes=["DeepseekBlock"]

RAM 부족 문제

  • TPU로 연결해서 해결하기?
  • 로컬에서 해보려고 했는데 도커 깔고 이거저거 할 거 많은 와중에 내 컴퓨터도 아녀서 시도 안하기로..
  • 그냥 코랩 유료 결제하고 A100 사용

4-bit quantization process is encountering a data type mismatch

Blockwise quantization only supports 16/32-bit floats, but got torch.uint8

해결 방법

Possible Solution 1:
To address the first and second hypotheses, try disabling the load_in_4bit option when loading the model.

# 모델 초기화
model = AutoModelForCausalLM.from_pretrained(
    model_name,
    device_map="auto",
    torch_dtype=torch.float16,
    offload_folder=offload_folder,
    low_cpu_mem_usage=True,
    # Remove or set load_in_4bit=False
    # quantization_config=quantization_config 
).to_empty(device="cuda")
Use code with caution
Explanation: Since the weights of the model are already quantized to 4bit on download, using load_in_4bit=True might lead to attempting to quantize them again. By disabling or not using the config, it is expected the weights will be loaded normally.

Possible Solution 2:
To address the second and third hypotheses, try changing the quantization type to "fp4"

quantization_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_compute_dtype=torch.float16,
    bnb_4bit_quant_type="fp4" # Change the quant type to fp4
)
Use code with caution
Explanation: The quantization type "nf4" (normal float 4) might not be compatible with the loading procedure or model architecture. Switching to "fp4" (floating point 4) could resolve the data type conflict and enable loading the model successfully.

By applying these changes, you're either loading the pre-quantized model as is, avoiding further quantization, or attempting to load with a configuration that is more compatible with the existing data type. This should prevent the "ValueError" and allow the code to execute correctly.

  • 첫 번째 방법으로 해결함
    - 이제 의미를 담은 말을 반환하긴 하는데 너무 짧거나 의도에서 벗어난 의미를 품고 있음

MeCab과 Mecab 혼용 문제

  • Konlpy Mecab을 썼어야 하는데 MeCab을 써서 생긴 문제
!git clone https://github.com/SOMJANG/Mecab-ko-for-Google-Colab.git
%cd Mecab-ko-for-Google-Colab
!bash install_mecab-ko_on_colab_light_220429.sh

CUDA out of memory

  • GPU 메모리 초과...
# 코드 최상단에 추가
import torch
torch.cuda.empty_cache()

# 환경 변수 설정 (메모리 단편화 감소)
import os
os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
  • 세션 끊고 다시 시작

풀어야할 문제

  1. 모델 실행 속도 올리기
  2. 모델 경량화
  3. 로딩 시간 줄이기
profile
🐬 파이썬 / 인공지능 / 머신러닝

0개의 댓글