DEV Community

matias yoon
matias yoon

Posted on

로컬 LLM 셋업 가이드 (v50)

로컬 LLM 셋업 가이드 (v50)

1. 개요 및 전제 조건

로컬 LLM(대형 언어 모델)은 클라우드 서비스 의존성에서 벗어나 개인 정보 보호와 성능 개선을 목표로 합니다. 이 가이드는 Linux 기반 시스템에서 최적의 로컬 LLM 환경을 구축합니다.

전제 조건:

  • Linux 시스템 (Ubuntu 20.04 이상 권장)
  • GPU: NVIDIA GTX 3060 이상 (CUDA 지원)
  • RAM: 최소 16GB, 권장 32GB 이상
  • 저장 공간: 최소 50GB 여유 공간

2. 프레임워크 비교

프레임워크 장점 단점 추천 사용 사례
llama.cpp 빠른 성능, CPU/ GPU 모두 지원, 최소 의존성 복잡한 설치 과정, 직접 컴파일 필요
Ollama 간단한 설치, 커뮤니티 지원, GUI 포함 메모리 사용량이 높음
vLLM 초고속 추론, 대규모 모델 처리 복잡한 설정, 최신 CUDA 필요
LocalAI REST API 기반, 다양한 모델 지원 빌드가 필요하며 상대적으로 오래 걸림

추천: 단순하고 빠른 구동을 원한다면 llama.cpp를 사용하세요. 빠른 프로토타이핑과 높은 성능을 원한다면 Ollama 또는 vLLM을 고려하세요.

3. 설치 단계 (llama.cpp 기반)

3.1 의존성 설치

sudo apt update
sudo apt install -y build-essential git cmake python3-pip
pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118
Enter fullscreen mode Exit fullscreen mode

3.2 llama.cpp 설치

cd /opt
git clone https://github.com/ggerganov/llama.cpp.git
cd llama.cpp
make clean
make -j$(nproc)
Enter fullscreen mode Exit fullscreen mode

3.3 모델 다운로드 및 변환

# 모델 다운로드
mkdir -p models
cd models
wget https://huggingface.co/TheBloke/Mistral-7B-v0.1-GGUF/resolve/main/mistral-7b-v0.1.Q4_K_M.gguf
Enter fullscreen mode Exit fullscreen mode

3.4 실행 테스트

cd /opt/llama.cpp
./main -m models/mistral-7b-v0.1.Q4_K_M.gguf -p "Hello, how are you?" --temp 0.7
Enter fullscreen mode Exit fullscreen mode

4. 모델 선택 가이드

4.1 개발자용 모델

모델 메모리 요구량 추천 사례 양자화
Mistral-7B-v0.1 4GB 일반 텍스트 생성 Q4_K_M
Llama-3-8B 8GB 코드 생성, 복잡한 대화 Q5_K_M
Phi-3-mini 2GB 빠른 추론 Q4_K_M

4.2 실제 예제

# Mistral-7B 실행
./main -m models/mistral-7b-v0.1.Q4_K_M.gguf -p "Write a Python function to calculate factorial" --temp 0.3 -n 150
Enter fullscreen mode Exit fullscreen mode

5. 양자화 유형 설명

5.1 Q4_K_M vs Q5_K_M

  • Q4_K_M: 4비트 양자화, 최대 압축률
  • Q5_K_M: 5비트 양자화, 정확도 향상

5.2 변환 명령어

# GGUF로 변환
python3 convert-hf-to-gguf.py /path/to/model --outtype q4_k_m --outfile model.Q4_K_M.gguf
Enter fullscreen mode Exit fullscreen mode

5.3 성능 비교

# Q4_K_M vs Q5_K_M 성능 테스트
time ./main -m model.Q4_K_M.gguf -p "Test prompt" --temp 0.7 -n 100
time ./main -m model.Q5_K_M.gguf -p "Test prompt" --temp 0.7 -n 100
Enter fullscreen mode Exit fullscreen mode

6. API 설정 및 통합

6.1 FastAPI 서버 구축

# server.py
from fastapi import FastAPI
from pydantic import BaseModel
import subprocess

app = FastAPI()

class PromptRequest(BaseModel):
    prompt: str
    model: str = "mistral-7b-v0.1.Q4_K_M.gguf"

@app.post("/generate")
async def generate_text(request: PromptRequest):
    cmd = f"./main -m models/{request.model} -p \"{request.prompt}\" --temp 0.7 -n 150"
    result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
    return {"response": result.stdout}
Enter fullscreen mode Exit fullscreen mode

6.2 서버 실행

pip install fastapi uvicorn
uvicorn server:app --host 0.0.0.0 --port 8000
Enter fullscreen mode Exit fullscreen mode

6.3 API 호출 예제

curl -X POST http://localhost:8000/generate \
  -H "Content-Type: application/json" \
  -d '{"prompt": "Explain quantum computing in simple terms"}'
Enter fullscreen mode Exit fullscreen mode

7. 시스템 서비스 설정

7.1 systemd 서비스 파일 생성

sudo nano /etc/systemd/system/llm.service
Enter fullscreen mode Exit fullscreen mode
[Unit]
Description=Local LLM Service
After=network.target

[Service]
Type=simple
User=developer
WorkingDirectory=/opt/llama.cpp
ExecStart=/opt/llama.cpp/main -m /opt/llama.cpp/models/mistral-7b-v0.1.Q4_K_M.gguf -p "Hello" --port 8080
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
Enter fullscreen mode Exit fullscreen mode

7.2 서비스 시작

sudo systemctl daemon-reload
sudo systemctl enable llm
sudo systemctl start llm
sudo systemctl status llm
Enter fullscreen mode Exit fullscreen mode

8. 모니터링 및 성능 튜닝

8.1 메모리 사용량 추적

# 실시간 모니터링
watch -n 1 nvidia-smi

# 메모리 사용량 확인
free -h
Enter fullscreen mode Exit fullscreen mode

8.2 성능 최적화 설정

# CPU 스레드 설정
./main -m models/mistral-7b-v0.1.Q4_K_M.gguf -p "Test" --temp 0.7 -n 100 -t 8

# GPU 메모리 최적화
./main -m models/mistral-7b-v0.1.Q4_K_M.gguf -p "Test" --temp 0.7 -n 100 --ctx-size 2048 --gpu-layers 30
Enter fullscreen mode Exit fullscreen mode

8.3 로그 수집

# 로그 저장
sudo journalctl -u llm -f > /var/log/llm.log

# 성능 로그
./main -m models/mistral-7b-v0.1.Q4_K_M.gguf -p "Test" --temp 0.7 -n 100 -v
Enter fullscreen mode Exit fullscreen mode

9. 실제 사용 사례

9.1 코드 생성 예제

# Python 코드 생성
./main -m models/mistral-7b-v0.1.Q4_K_M.gguf -p "Write a Python script that reads CSV and displays statistics" --temp 0.3 -n 200
Enter fullscreen mode Exit fullscreen mode

9.2 문제 해결 예제

# 디버깅 도우미
./main -m models/mistral-7b-v0.1.Q4_K_M.gguf -p "I'm getting 'ModuleNotFoundError' for pandas. How to fix it?" --temp 0.5 -n 150
Enter fullscreen mode Exit fullscreen mode

9.3 성능 기준

작업 시간 메모리
단순 텍스트 생성 0.2초 3GB
코드 생성 0.8초 4GB
복잡한 질문 답변 1.2초 5GB

10. 고급 설정 및 문제 해결


📥 Get the full guide on Gumroad: https://gumroad.com/l/auto ($7)

Top comments (0)