본문 바로가기
Python

[Python] Hugging Face Transformers로 텍스트 생성하기 (CPU에서도 가능)

by teamnova 2025. 9. 4.
728x90

최근 LLM(대규모 언어 모델)이 다양하게 개발되고 있습니다.
고성능 서버가 아니더라도 직접 로컬에서 작은 모델을 사용해볼 수 있는데요
이번 글에서는 Hugging Face의 Transformers 라이브러리를 활용해 텍스트를 생성해보겠습니다!

 

 

 

1. 환경 준비 

먼저 가상 환경(venv)을 만들고 필요한 라이브러리를 설치합니다.

pip install transformers torch

 

 

2. 실행 코드

아래 코드를 run_test.py 로 저장하고 실행해봅시다.
여기서는 facebook/opt-125m 모델을 사용합니다. (약 120M 파라미터로 CPU에서도 빠르게 동작)

- opt-125m, distilgpt2 같은 작은 모델을 추천

from transformers import AutoTokenizer, AutoModelForCausalLM

model_name = "facebook/opt-125m"

# 1. 모델과 토크나이저 로드
print("Loading model and tokenizer...")
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name)
print("Model loaded successfully on CPU.")

# 2. 프롬프트 준비
prompt = "My favorite food in this world is"
inputs = tokenizer(prompt, return_tensors="pt")

# 3. 텍스트 생성
print("Generating text...")
outputs = model.generate(
    **inputs,
    max_new_tokens=50,
    do_sample=True,
    temperature=0.8,
    top_p=0.95,
)

# 4. 결과 출력
generated_text = tokenizer.batch_decode(outputs, skip_special_tokens=True)[0]

print("---")
print(f"Prompt: {prompt!r}")
print(f"Generated text: {generated_text!r}")

 

 

 

답변

 

프롬프트: "My favorite food in this world is"

생성 텍스트(LLM 생성 대답) :  "My favorite food in this world is grilled cheese. I go to the pizza place when I go to my local pizza place, and it's the best grilled cheese there is! It's very good, and I really like grilled cheese sandwiches, too!\nYeah, it's so good"

 

 

감사합니다.