Llama 3 소개
Meta의 Llama (Large Language Model Meta AI)는 2023년 출시 이후 오픈소스 LLM 생태계의 표준이 된 모델입니다. Llama 3.1부터는 Apache 2.0 라이선스로 상업적 사용이 가능하며, 128K 컨텍스트 윈도우와 다국어(한국어 포함) 지원을 제공합니다.
주요 특징
- 오픈 웨이트 — 모델 가중치를 자유롭게 다운로드·수정·배포
- 128K 컨텍스트 — 긴 문서 처리, 멀티턴 대화에 적합
- 다국어 지원 — 한국어, 영어, 독일어, 프랑스어, 중국어 등
- Tool Use — 함수 호출(Function Calling) 기본 지원
- 다양한 크기 — 1B부터 405B까지 용도에 맞게 선택 가능
모델 라인업
| 모델 | 파라미터 | VRAM 요구량 | 특징 |
|---|---|---|---|
| Llama 3.2 | 1B, 3B | 2~4GB | 모바일·엣지 디바이스용 경량 모델 |
| Llama 3.1 / 3.3 | 8B | 6~8GB | 개인 GPU 적합, 균형 잡힌 성능 |
| Llama 3.1 | 70B | 40~48GB | 전문 업무용, GPT-3.5 수준 |
| Llama 3.1 | 405B | 200GB+ | GPT-4 수준, 데이터센터 배포 |
처음 시작한다면: RTX 3060(12GB) 이상이라면 Llama 3.1 8B, 16GB 이하 RAM 환경이라면 Llama 3.2 3B를 권장합니다.
Ollama로 실행 (가장 간단)
Ollama는 오픈소스 LLM을 로컬에서 실행하는 가장 빠른 방법입니다. Docker처럼 명령 한 줄로 모델을 받고 실행합니다.
Ollama 설치
# macOS / Linux
curl -fsSL https://ollama.com/install.sh | sh
# Windows: https://ollama.com/download 에서 설치
# 설치 확인
ollama --versionbash
Llama 실행
# Llama 3.2 3B (가벼운 버전)
ollama run llama3.2
# Llama 3.1 8B
ollama run llama3.1
# Llama 3.1 70B (대용량)
ollama run llama3.1:70b
# 백그라운드 서버 실행
ollama serve &bash
Ollama REST API
# 채팅 완성
curl http://localhost:11434/api/chat -d '{
"model": "llama3.1",
"messages": [
{ "role": "user", "content": "한국의 수도는 어디인가요?" }
],
"stream": false
}'
# 텍스트 생성
curl http://localhost:11434/api/generate -d '{
"model": "llama3.1",
"prompt": "FastAPI란 무엇인가?",
"stream": false
}'bash
llama.cpp 설치 (CPU/GPU 최적화)
llama.cpp는 C++로 구현된 고성능 LLM 추론 엔진입니다. CPU만으로도 실용적인 속도를 제공합니다.
# 소스 빌드
git clone https://github.com/ggerganov/llama.cpp
cd llama.cpp
# CPU 전용 빌드
make -j4
# CUDA(NVIDIA GPU) 빌드
make LLAMA_CUDA=1 -j4
# Metal(Apple Silicon) 빌드
make LLAMA_METAL=1 -j4bash
GGUF 모델 다운로드 및 실행
# Hugging Face에서 GGUF 형식 다운로드
pip install huggingface_hub
huggingface-cli download \
bartowski/Meta-Llama-3.1-8B-Instruct-GGUF \
Meta-Llama-3.1-8B-Instruct-Q4_K_M.gguf \
--local-dir ./models
# 대화형 실행
./llama-cli \
-m ./models/Meta-Llama-3.1-8B-Instruct-Q4_K_M.gguf \
--chat-template llama3 \
-n 512 -c 4096bash
Hugging Face 활용
모델 다운로드
라이선스 동의 필요: Meta Llama 모델은 Hugging Face에서 라이선스에 동의해야 다운로드 가능합니다. huggingface.co/meta-llama에서 동의 후 토큰을 발급하세요.
pip install transformers accelerate bitsandbytes huggingface_hub
# HF 토큰 설정
huggingface-cli login # 또는 환경변수 HF_TOKEN 설정bash
Python 추론
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
model_id = "meta-llama/Llama-3.1-8B-Instruct"
# 토크나이저 & 모델 로드
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
model_id,
torch_dtype=torch.bfloat16,
device_map="auto", # GPU 자동 할당
)
# 파이프라인 생성
pipe = pipeline(
"text-generation",
model=model,
tokenizer=tokenizer,
max_new_tokens=512,
temperature=0.7,
do_sample=True,
)
# 메시지 구성 (Llama 3 Chat 형식)
messages = [
{"role": "system", "content": "당신은 친절한 한국어 AI 어시스턴트입니다."},
{"role": "user", "content": "파이썬에서 데코레이터란 무엇인가요?"},
]
# 추론 실행
output = pipe(messages)
print(output[0]["generated_text"][-1]["content"])python
OpenAI 호환 API 서버
Ollama나 vLLM을 사용해 OpenAI API와 동일한 인터페이스로 Llama를 서빙합니다.
Ollama OpenAI 호환 엔드포인트
# Ollama는 기본으로 OpenAI 호환 API 제공
# http://localhost:11434/v1/
from openai import OpenAI
client = OpenAI(
base_url="http://localhost:11434/v1",
api_key="ollama", # 임의 값
)
response = client.chat.completions.create(
model="llama3.1",
messages=[
{"role": "system", "content": "당신은 코딩 전문가입니다."},
{"role": "user", "content": "Python async/await를 설명해주세요."},
],
temperature=0.7,
max_tokens=1024,
)
print(response.choices[0].message.content)python
Python 활용 패턴
스트리밍 응답
import ollama
stream = ollama.chat(
model='llama3.1',
messages=[{'role': 'user', 'content': '대한민국의 역사를 설명해주세요.'}],
stream=True,
)
for chunk in stream:
print(chunk['message']['content'], end='', flush=True)python
구조화된 출력 (JSON Mode)
import json
import ollama
response = ollama.chat(
model='llama3.1',
messages=[{
'role': 'user',
'content': '서울의 날씨 정보를 JSON 형태로 알려주세요. {"city", "temperature", "condition"} 형식으로.',
}],
format='json',
)
data = json.loads(response['message']['content'])
print(data)python
LangChain 연동
pip install langchain langchain-community
from langchain_community.llms import Ollama
from langchain_core.prompts import ChatPromptTemplate
llm = Ollama(model="llama3.1", temperature=0.7)
prompt = ChatPromptTemplate.from_messages([
("system", "당신은 유능한 Python 개발자입니다."),
("human", "{question}"),
])
chain = prompt | llm
result = chain.invoke({"question": "FastAPI로 간단한 REST API를 만드는 방법은?"})
print(result)python
RAG (검색 증강 생성) 구현
pip install langchain langchain-community chromadb sentence-transformers
from langchain_community.vectorstores import Chroma
from langchain_community.embeddings import OllamaEmbeddings
from langchain_community.llms import Ollama
from langchain.chains import RetrievalQA
from langchain.schema import Document
# 문서 준비
docs = [
Document(page_content="FastAPI는 Python 기반의 고성능 웹 프레임워크입니다."),
Document(page_content="Pydantic으로 데이터 검증을 자동화할 수 있습니다."),
]
# 벡터 저장소 생성
embeddings = OllamaEmbeddings(model="llama3.1")
vectorstore = Chroma.from_documents(docs, embeddings)
# RAG 체인 구성
llm = Ollama(model="llama3.1")
qa_chain = RetrievalQA.from_chain_type(
llm=llm,
retriever=vectorstore.as_retriever(search_kwargs={"k": 2}),
)
result = qa_chain.invoke("FastAPI의 특징은?")
print(result['result'])python
양자화 (Quantization)
| 방식 | 메모리 | 속도 | 품질 | 추천 용도 |
|---|---|---|---|---|
| FP16 (반정밀도) | 16GB | 빠름 | 최상 | A100, H100 |
| INT8 (8비트) | 8GB | 보통 | 우수 | RTX 3090 |
| INT4 (4비트 NF4) | 5GB | 보통 | 양호 | RTX 3060 12GB |
| GGUF Q4_K_M | 4.8GB | CPU도 가능 | 양호 | CPU 서버, Mac |
GPU 요구사항
| 모델 | 최소 VRAM | 권장 GPU |
|---|---|---|
| Llama 3.2 1B | 2GB | GTX 1660, M1/M2 Mac |
| Llama 3.2 3B | 4GB | RTX 3050, M1 Pro |
| Llama 3.1 8B (INT4) | 5GB | RTX 3060 12GB |
| Llama 3.1 8B (FP16) | 16GB | RTX 4080, A10G |
| Llama 3.1 70B (INT4) | 40GB | A100 40GB, 2×RTX 4090 |