DEV Community

matias yoon
matias yoon

Posted on

로컬 LLM 셋업 가이드 (v9)

로컬 LLM 셋업 가이드 (v9)

1. 개요 및 사전 요구사항

로컬 LLM은 인터넷 연결 없이도 AI 추론을 수행할 수 있게 해줍니다. 이 가이드는 Linux 환경에서 최적화된 로컬 LLM셋업을 구축하는 실용적인 방법을 제공합니다.

사전 요구사항:

  • Linux (Ubuntu 22.04 이상 권장)
  • GPU: NVIDIA RTX 30xx 이상 (12GB RAM 이상 권장)
  • RAM: 최소 16GB, 32GB 이상 권장
  • 저장공간: 최소 50GB (모델 파일 포함)
# 시스템 정보 확인
lspci | grep -i nvidia
free -h
df -h
Enter fullscreen mode Exit fullscreen mode

2. 프레임워크 비교

프레임워크 장점 단점 적합성
llama.cpp C++로 작성, 최소 의존성, GPU 지원 메모리 사용량 높음 간단한 사용자 또는 개발자
Ollama 쉬운 CLI 인터페이스, Docker 기반 이미지 크기 큼 빠른 프로토타이핑
vLLM 고속 추론, 다중 GPU 지원 복잡한 설정 필요 고성능 서버 환경
LocalAI REST API, 다양한 모델 지원 최신 버전에 대한 문서 부족 API 기반 개발

권장: llama.cpp + Ollama 조합 (기본 설치) + LocalAI (API 통합)

3. 설치 단계

3.1 llama.cpp 설치

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

3.2 Ollama 설치 (선택적)

# Ollama 설치
curl -fsSL https://ollama.com/install.sh | sh
# 서비스 시작
systemctl start ollama
systemctl enable ollama
Enter fullscreen mode Exit fullscreen mode

3.3 가상환경 설정

# Python 가상환경 생성
python3 -m venv llama-env
source llama-env/bin/activate
pip install torch transformers accelerate
Enter fullscreen mode Exit fullscreen mode

4. 모델 선택 가이드

4.1 모델별 사용 사례

모델 크기 사용 사례 추천
Mistral-7B 7B 일반 텍스트 생성
LLaMA3-8B 8B 고급 추론
Phi-3 3B 가벼운 작업
Gemma-2B 2B 빠른 프로토타입
# 모델 다운로드 예시
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

5. 양자화 유형 설명

양자화 설명 성능
Q4_K_M K-quants, 최적화된 Q4 최고 성능
Q5_K_M K-quants, Q5 품질 균형 잡힌 성능
Q6_K K-quants, 고품질 품질 높음
Q8_0 8비트 양자화 높은 품질
# 양자화 명령어 예시
./llama.cpp/quantize mistral-7b-v0.1.Q4_K_M.gguf mistral-7b-v0.1.Q5_K_M.gguf Q5_K_M
Enter fullscreen mode Exit fullscreen mode

6. API 설정 및 통합

6.1 llama.cpp API 서버 실행

# 모델로 서버 실행
./llama.cpp/server -m ./models/mistral-7b-v0.1.Q5_K_M.gguf \
  --port 8080 \
  --host 0.0.0.0 \
  --threads 8 \
  --ctx-size 2048
Enter fullscreen mode Exit fullscreen mode

6.2 Python API 통합 예제

import requests

def call_llm(prompt, base_url="http://localhost:8080"):
    response = requests.post(
        f"{base_url}/completion",
        json={
            "prompt": prompt,
            "n_predict": 128,
            "temperature": 0.7
        }
    )
    return response.json()['content']

# 사용 예시
result = call_llm("Python으로 REST API를 만드는 방법은?")
print(result)
Enter fullscreen mode Exit fullscreen mode

7. Systemd 서비스 설정

# 서비스 파일 생성
sudo nano /etc/systemd/system/llama.service
Enter fullscreen mode Exit fullscreen mode
[Unit]
Description=LLaMA Server
After=network.target

[Service]
Type=simple
User=your_user
WorkingDirectory=/home/your_user/llama.cpp
ExecStart=/home/your_user/llama.cpp/server -m /home/your_user/models/mistral-7b-v0.1.Q5_K_M.gguf --port 8080 --host 0.0.0.0 --threads 8 --ctx-size 2048
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
Enter fullscreen mode Exit fullscreen mode
# 서비스 등록 및 시작
sudo systemctl daemon-reload
sudo systemctl enable llama.service
sudo systemctl start llama.service
sudo systemctl status llama.service
Enter fullscreen mode Exit fullscreen mode

8. 모니터링 및 성능 튜닝

8.1 시스템 모니터링

# GPU 사용량 모니터링
nvidia-smi -l 1

# CPU 및 메모리 모니터링
htop

# 로그 확인
journalctl -u llama.service -f
Enter fullscreen mode Exit fullscreen mode

8.2 성능 향상을 위한 설정

# 커널 파라미터 최적화
echo 'vm.swappiness=1' | sudo tee -a /etc/sysctl.conf
echo 'vm.dirty_ratio=15' | sudo tee -a /etc/sysctl.conf
sudo sysctl -p

# CPU 스케줄링 최적화
echo 'performance' | sudo tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor
Enter fullscreen mode Exit fullscreen mode

9. 실제 사용 예시

9.1 성능 벤치마크

# llama.cpp 벤치마크 실행
./llama.cpp/benchmark -m ./models/mistral-7b-v0.1.Q5_K_M.gguf -n 128 -t 8 --threads 8

# 결과 예시
# Tokens per second: 22.4
# Total time: 5.7s
Enter fullscreen mode Exit fullscreen mode

9.2 실제 애플리케이션 예제

# docker-compose.yml 예시
version: '3.8'
services:
  llama-server:
    image: localai/localai:latest-cpu
    command: local-ai --port 8080
    volumes:
      - ./models:/models
    ports:
      - "8080:8080"
    environment:
      - MODELS_PATH=/models
Enter fullscreen mode Exit fullscreen mode

9.3 클라이언트 테스트

# curl 테스트
curl -X POST http://localhost:8080/completion \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "Write a Python function to calculate fibonacci numbers.",
    "n_predict": 64,
    "temperature": 0.3
  }'
Enter fullscreen mode Exit fullscreen mode

9.4 성능 최적화 커맨드

# 메모리 최적화
export CUDA_LAUNCH_BLOCKING=0
export CUDA_DEVICE_MAX_CONNECTIONS=1

# CPU 스레드 최적화
export OMP_NUM_THREADS=8
export MKL_NUM_THREADS=8
Enter fullscreen mode Exit fullscreen mode

10. 결론

이 가이드는 실제 개발 환경에서 로컬 LLM을 구축하고 운영하는 실용적인 방법을 제공합니다. 다음은 핵심 요약입니다:

  1. 환경: Ubuntu 22.04 + RTX 4090 + 32GB RAM
  2. 프레임워크: llama.cpp + Ollama 조합
  3. 모델: Mistral-7B (Q5_K_M 양자화)
  4. API: REST API로 쉽게 통합 가능
  5. 운영: Systemd 서비스로 24/7 운영

이 설정은 개발 프로젝트에서 LLM을 로컬에서 효율적으로 사용할 수 있도록 해줍니다


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

Top comments (0)