Huggingface로 LLM 실행하기

결과 영상

SveltKit + FastAPI를 이용해 LLM을 모바일에서 사용한 예시다. Github


Huggingface Token

Huggingface🤗에서 LLM을 다운로드하기 위해 Token을 발급받아야 한다. 한 번 발급받은 토큰은 다시 확인이 어려우니 잘 기억해 두자.

Settings > Access Tokens > + Create new token


모델 실행

모델을 Local에서 사용하기는 어려우니 Colab에서 시도하는 걸 추천한다. 필자는 RTX4060(8GB)를 이용해 로컬에서 겨우 돌렸다.

!pip install transformers torch huggingface_hub bitsandbytes

먼저 필요한 패키지를 설치해 준다.

from huggingface_hub import login
login()

이 코드를 실행하면 token을 입력하라는 창이 뜨는데, 이전 단계에서 받은 token을 입력하면 된다.

from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
import torch

# Download model and tokenizer
model_name = "mistralai/Mistral-7B-v0.1"

# Quantization to load model on small VRAM
quantization_config = BitsAndBytesConfig(
    load_in_4bit=True,  # Enable 4-bit quantization
    bnb_4bit_compute_dtype=torch.float16,  # Computation precision
    bnb_4bit_use_double_quant=True,  # Enable nested quantization for further memory optimization
    bnb_4bit_quant_type="nf4",  # Quantization type
)

tokenizer = AutoTokenizer.from_pretrained(model_name, token=True)
model = AutoModelForCausalLM.from_pretrained(
    model_name, quantization_config=quantization_config, device_map="auto", token=True
)

model.save_pretrained("./mistral")
tokenizer.save_pretrained("./mistral")

본 예제는 비교적 가벼운 모델인 Mistral-7B-v0.1을 사용한다. 하지만 "Large" Language model 답게 작은 모델조차도 Colab에서 돌리기 힘들다. 따라서 4-bit quantization을 사용한다. Pytorch는 모델 가중치를 저장할 때 기본으로 32-bit를 사용한다. 그렇게 하면 모델이 매우 커지기 때문에 가중치를 4-bit로 두고 계산하는 방법이다. 당연하게도 정확도는 조금 떨어지겠지만, 이렇게 하지 않으면 돌릴 수 조차 없다.

모델 재사용을 위해 save_pretrained를 통해 model과 tokenizer를 저장해 줬다.

# Define a prompt
prompt = "Explain ADHD symptoms."

# Tokenize input
inputs = tokenizer(prompt, return_tensors="pt").to("cuda")

# Generate output
with torch.no_grad():
    output = model.generate(
        **inputs, max_length=200, pad_token_id=tokenizer.eos_token_id
    )

# Decode and print the output
response = tokenizer.decode(output[0], skip_special_tokens=True)
print(response)

이제 프롬프트를 작성하고, tokenizer → model 순서로 입력하면 답변을 생성한다.

Explain ADHD symptoms.

Attention deficit hyperactivity disorder (ADHD) is a neurodevelopmental disorder that is characterized by a pattern of inattention and/or hyperactivity-impulsivity that is more frequent and severe than is typically observed in individuals at a comparable level of development.

The symptoms of ADHD are divided into two categories: inattention and hyperactivity-impulsivity.

Inattention symptoms include:

- Difficulty paying attention to details or making careless mistakes in schoolwork, work, or other activities
- Difficulty sustaining attention in tasks or play activities
- Difficulty organizing tasks and activities
- Avoidance or dislike of tasks that require sustained mental effort, such as schoolwork or homework
- Losing things necessary for tasks or activities, such as school supplies, pencils, books, tools, wallets, keys, paperwork, eyeglass