AI

Hugging Face에서 LLaMA 실행하는 3가지 방법

B컷개발자 2025. 4. 15. 11:40

Hugging Face에서 LLaMA 실행하는 3가지 방법 – 코드 예제 포함

LLaMA 모델을 Hugging Face에서 쉽게 실행하는 방법 3가지를 소개합니다.
GPT 대신 로컬 또는 서버에서 오픈소스 LLM을 직접 실행하고 싶은 분들을 위한 실습형 가이드입니다.


✳️ 글을 시작하며

Meta AI의 LLaMA 3 시리즈는 Hugging Face Hub를 통해 바로 사용할 수 있도록 공개되어 있습니다.
하지만 처음 접하는 사람에게는 실행 방식이 조금 어렵게 느껴질 수 있습니다.

이 글에서는 다음 3가지 방법을 중심으로 가장 많이 사용되는 LLaMA 실행 방식을 정리합니다.


✅ 사전 준비 사항

  1. Hugging Face 계정 생성 및 토큰 발급
  2. transformers, accelerate 패키지 설치
  3. 모델 접근 권한 요청 (예: meta-llama/Llama-3-8b-instruct)
pip install transformers accelerate

방법 ① Transformers + AutoModel 직접 사용하기

가장 기본적인 방식이며, 모델 로딩 후 직접 텍스트 생성이 가능합니다.

from transformers import AutoTokenizer, AutoModelForCausalLM

model_id = "meta-llama/Llama-3-8b-instruct"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto")

prompt = "LLaMA 모델의 장점은 무엇인가요?"
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
outputs = model.generate(**inputs, max_new_tokens=100)
print(tokenizer.decode(outputs[0], skip_special_tokens=True))

🔹 장점: 가장 직관적이고, 로컬 GPU 환경에서 바로 실행 가능
🔹 단점: 서버 리소스가 부족한 경우 실행이 어려울 수 있음


방법 ② Transformers Pipeline으로 간단 실행

텍스트 생성 파이프라인으로 단 몇 줄 코드로 실행 가능합니다.

from transformers import pipeline

pipe = pipeline("text-generation", model="meta-llama/Llama-3-8b-instruct", device_map="auto")
result = pipe("LLaMA와 GPT-4의 차이점은?", max_new_tokens=100)
print(result[0]['generated_text'])

🔹 장점: 초보자에게 친화적
🔹 단점: 세부 제어가 어려움 (beam search, temperature 조절 등)


방법 ③ Text Generation Inference 서버 실행 (고성능)

text-generation-inference 패키지를 사용해 API 서버로 모델 실행이 가능합니다.
대규모 서비스용으로 적합하며, Docker 기반 실행도 가능합니다.

pip install text-generation
text-generation-launcher --model-id meta-llama/Llama-3-8b-instruct

API 서버가 열리며, 다음과 같이 요청할 수 있습니다.

import requests
response = requests.post(
    "http://localhost:8080/generate",
    json={"inputs": "LLaMA 모델이란?", "parameters": {"max_new_tokens": 100}}
)
print(response.json())

🔹 장점: 고성능 배포에 적합, API 기반 호출 가능
🔹 단점: 메모리 24GB 이상 필요 (70B 기준 80GB 이상)


⚙️ 실행 팁과 최적화 전략

  • 모델 로딩 시간 단축: torch_dtype=torch.bfloat16 옵션 사용
  • 메모리 부족 시: 4bit/8bit quantization 적용 (bitsandbytes)
  • 로컬 개발 테스트 시는 meta-llama/Llama-2-7b-chat-hf로 대체 가능

결론: 어떤 방법이 나에게 맞을까?

목적 추천 실행 방식

로컬 테스트 방법 ① (AutoModel)
간단 테스트 방법 ② (pipeline)
고성능 서비스용 방법 ③ (Inference API 서버)

LLaMA는 Hugging Face에서 매우 유연하게 사용할 수 있는 모델입니다.
이제는 GPT API를 꼭 쓸 필요 없이, 직접 모델을 다룰 수 있는 환경이 마련되어 있습니다.


Hugging Face에서 LLaMA 모델을 실행하는 3가지 방법을 정리했습니다. transformers, pipeline, inference 서버 방식까지 코드 예제와 함께 제공합니다.


다음 연재 예정 글

→ [5편] LLaMA 로컬 설치 가이드 – llama.cpp 기반 실습
→ [6편] 16GB 램에서 LLaMA 7B 실행하기