DEV Community

matias yoon
matias yoon

Posted on

로컬 LLM 셋업 가이드 (v47)

로컬 LLM 셋업 가이드 (v47)

1. 개요 & 사전 요구사항

로컬 LLM (Large Language Model) 실행은 클라우드 비용 절감과 개인정보 보호를 위해 매우 효과적인 접근법입니다. 이 가이드는 최소한의 리소스로도 실행 가능한 설정을 제공합니다.

시스템 요구사항:

  • OS: Ubuntu 22.04 이상 (또는 다른 Debian 기반 Linux)
  • CPU: 64비트 x86_64
  • RAM: 최소 8GB (16GB 이상 권장)
  • GPU: NVIDIA RTX 3060 이상 (CUDA 지원)
  • 디스크: 20GB 이상 여유 공간

필수 패키지 설치:

sudo apt update
sudo apt install -y git cmake build-essential python3-pip
Enter fullscreen mode Exit fullscreen mode

2. 프레임워크 비교

프레임워크 장점 단점 적합성
llama.cpp 최소한의 리소스, 직접 컴파일 필요 복잡한 설치 과정 고급 사용자
Ollama 간단한 설치, 커뮤니티 모델 지원 특정 모델 제한 개발자
vLLM 높은 성능, 대량 요청 처리 고급 설정 필요 엔터프라이즈
LocalAI API 기반, 다양한 모델 지원 리소스 소비량 큼 빠른 프로토타이핑

추천: Ollama + llama.cpp 조합 (간편한 설치 + 높은 성능)

3. 설치 가이드

Ollama 설치 (권장)

# Ollama 설치
curl -fsSL https://ollama.com/install.sh | sh

# 서비스 시작
sudo systemctl start ollama
sudo systemctl enable ollama

# Ollama 상태 확인
ollama ps
Enter fullscreen mode Exit fullscreen mode

llama.cpp 설치 (고급 사용)

# 소스코드 다운로드
git clone https://github.com/ggerganov/llama.cpp.git
cd llama.cpp

# 컴파일 (GPU 지원)
make clean
make -j$(nproc) LLAMA_CUDA=1

# 모델 다운로드 및 변환
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

4. 모델 선택 가이드

모델 크기 용도 추천 사용 사례
Mistral-7B-v0.1-Q4_K_M 3.8GB 일반 텍스트 생성 코드 생성, 요약
Mixtral-8x7B-v0.1-Q4_K_M 15GB 복잡한 작업 복합 프롬프트
Llama-3-8B-Q4_K_M 4.2GB 빠른 추론 데모, 테스트
Phi-3-mini-128k-Q4_K_M 2.3GB 텍스트 처리 문서 분석

실제 모델 로드 예제:

# Ollama에서 모델 다운로드
ollama pull mistral

# llama.cpp에서 직접 실행
./main -m ./mistral-7b-v0.1.Q4_K_M.gguf -p "Hello world" --temp 0.7
Enter fullscreen mode Exit fullscreen mode

5. 양자화 유형 설명

Q4_K_M: 최적화된 4비트 양자화 (기본推荐)
Q5_K_M: 5비트 양자화 (더 높은 정확도)
Q8_0: 8비트 양자화 (정확도 최대, 공간 사용량 증가)

# 모델 변환 명령어
./convert-hf-to-gguf.py --model-path ./mistral-7b-v0.1 --output ./mistral-7b-v0.1-Q4_K_M.gguf --quantize Q4_K_M
Enter fullscreen mode Exit fullscreen mode

6. API 설정 및 통합

Ollama API 사용

# 기본 API 테스트
curl http://localhost:11434/api/generate -d '{
  "model": "mistral",
  "prompt": "Python으로 hello world 프로그램을 작성해 주세요.",
  "stream": false
}'

# 응답 예시:
{
  "response": "def hello():\n    print(\"Hello, World!\")\n\nhello()",
  "done": true
}
Enter fullscreen mode Exit fullscreen mode

Python 클라이언트 예제

import requests
import json

def query_llm(prompt):
    response = requests.post('http://localhost:11434/api/generate',
                          json={
                              'model': 'mistral',
                              'prompt': prompt,
                              'stream': False
                          })
    return response.json()['response']

# 사용 예시
result = query_llm("오늘 날씨에 대해 설명해주세요.")
print(result)
Enter fullscreen mode Exit fullscreen mode

7. Systemd 서비스 설정

# 서비스 파일 생성
sudo nano /etc/systemd/system/ollama.service

# 서비스 내용:
[Unit]
Description=Ollama Service
After=network.target

[Service]
Type=simple
User=your_user
ExecStart=/usr/bin/ollama serve
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target

# 서비스 시작
sudo systemctl daemon-reload
sudo systemctl start ollama
sudo systemctl enable ollama
Enter fullscreen mode Exit fullscreen mode

8. 성능 모니터링 및 최적화

CPU/메모리 모니터링

# 실시간 모니터링
htop

# GPU 사용량 확인
nvidia-smi

# 로그 확인
journalctl -u ollama -f
Enter fullscreen mode Exit fullscreen mode

벤치마크 테스트

# llama.cpp 벤치마크
./main -m ./mistral-7b-v0.1.Q4_K_M.gguf -n 128 --temp 0.7

# Ollama 성능 테스트
ollama run mistral "한국어로 간단한 설명을 주세요."
Enter fullscreen mode Exit fullscreen mode

성능 기준:

  • 속도: 100토큰/초 이상
  • 메모리: 8GB 이상 사용 (모델별)
  • GPU: RTX 3060 이상 권장

최적화 설정

# 환경 변수 설정
export OLLAMA_NUM_PARALLEL=4
export OLLAMA_MAX_VRAM=8000000000

# 커스텀 모델 실행
ollama run --verbose mistral "test prompt"
Enter fullscreen mode Exit fullscreen mode

9. 실제 사용 사례

코드 생성 에이전트

# Python 코드 생성 프롬프트
ollama run mistral "다음 Python 코드를 작성해주세요: Flask 앱으로 웹 서버 생성, /api/hello 경로에 hello world 반환"

# 결과:
"""
from flask import Flask

app = Flask(__name__)

@app.route('/api/hello')
def hello():
    return 'Hello, World!'

if __name__ == '__main__':
    app.run()
"""
Enter fullscreen mode Exit fullscreen mode

문서 요약 서비스

# 빠른 요약
ollama run mistral "다음 문서를 300자 이내로 요약해주세요: [문서 내용]"
Enter fullscreen mode Exit fullscreen mode

10. 문제 해결

공통 오류 및 해결법

  1. GPU 메모리 부족
# 메모리 확인
nvidia-smi

# 모델 메모리 최적화
ollama run --num_ctx 2048 mistral
Enter fullscreen mode Exit fullscreen mode
  1. 서비스 시작 실패
# 로그 확인
journalctl -u ollama

# 권한 문제 해결
sudo chown -R $USER:$USER ~/.ollama
Enter fullscreen mode Exit fullscreen mode
  1. 모델 다운로드 실패
# 직접 다운로드
curl -L -o model.gguf "https://example.com/model.gguf"
Enter fullscreen mode Exit fullscreen mode

결론

로컬 LLM 셋업은 클라우드 비용 절감과 개인정보 보호를 동시에 달성할 수 있는 실용적인 방법입니다. Ollama와 llama.cpp 조합은 최적의 균형을 제공하며, 16GB RAM 이상의 시스템에서는 다양한 작업을 효율적으로 처리할 수 있습니다.

추천 작업 흐름:

  1. Ollama로 기본 설정
  2. 필요한 모델 다운로드
  3. Systemd 서비스로 자동 실행

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

Top comments (0)