Ollama와 vLLM으로 Gemma 3 27B 실행 완벽 설치 가이드

Google의 최신 오픈소스 언어 모델인 Gemma 3 27B는 단일 GPU에서 실행할 수 있는 모델 중 최고 성능을 자랑합니다. 이번 포스팅에서는 Ollama를 사용한 간편한 실행 방법과 고성능 추론을 위한 vLLM 설치 및 사용 방법을 자세히 알아보겠습니다.

Gemma 3 27B란?

Gemma 3 27B는 Google의 Gemini 2.0과 동일한 기술을 기반으로 개발된 270억 개 파라미터를 가진 오픈소스 언어 모델입니다. 멀티모달 기능을 지원하여 텍스트와 이미지를 함께 처리할 수 있으며, 128k 토큰의 긴 컨텍스트 윈도우와 140개 이상의 언어를 지원합니다.

주요 특징

  • 최고 성능: 단일 GPU에서 실행되는 모델 중 세계 최고 수준
  • 멀티모달: 텍스트와 이미지 동시 처리 가능
  • 긴 컨텍스트: 128,000 토큰까지 처리 가능
  • 다국어 지원: 140개 이상의 언어 지원
  • 함수 호출: 구조화된 출력 및 API 연동 기능

Ollama로 Gemma 3 실행하기

Ollama는 로컬 환경에서 대형 언어 모델을 쉽게 실행할 수 있게 해주는 도구입니다.

Ollama 설치

Windows/macOS:

Linux:

curl -fsSL https://ollama.ai/install.sh | sh

Gemma 3 27B 다운로드 및 실행

# 모델 다운로드 (약 16GB)
ollama pull gemma3:27b

# 대화형 모드 실행
ollama run gemma3:27b

# 단일 프롬프트 실행
ollama run gemma3:27b "한국의 전통 문화에 대해 설명해주세요"

멀티모달 기능 사용

# 이미지 분석 기능
ollama run gemma3:27b "이 이미지를 분석해주세요" --image ./photo.jpg

# 문서 OCR 기능
ollama run gemma3:27b "이 문서의 내용을 요약해주세요" --image ./document.png

API 서버 모드

# API 서버 시작
ollama serve

# RESTful API 호출
curl http://localhost:11434/api/generate -d '{
  "model": "gemma3:27b",
  "prompt": "Python으로 웹 스크래핑 코드를 작성해줘",
  "stream": false
}'

시스템 요구사항 및 최적화

최소 요구사항:

  • RAM: 32GB 이상 (권장 48GB)
  • GPU VRAM: 24GB 이상 (RTX 4090, RTX 6000 Ada 등)
  • 저장공간: 20GB 이상

최적화 설정:

# 환경 변수 설정
export OLLAMA_GPU_LAYERS=50
export OLLAMA_MAX_LOADED_MODELS=1
export OLLAMA_CONTEXT_SIZE=131072
export OLLAMA_KEEP_ALIVE=600

vLLM으로 Gemma 3 27B 고성능 서빙

vLLM은 대형 언어 모델을 위한 고성능 추론 및 서빙 엔진입니다. PagedAttention 등의 최적화 기술을 통해 Ollama보다 훨씬 빠른 속도와 높은 처리량을 제공합니다.

vLLM 설치 준비

시스템 요구사항:

  • Linux 운영체제 (Ubuntu 20.04+ 권장)
  • Python 3.9-3.12
  • NVIDIA GPU with CUDA 11.8 또는 12.1+
  • 최소 24GB GPU VRAM (27B 모델의 경우)

사전 준비:

# 시스템 업데이트
sudo apt update && sudo apt upgrade -y

# 필수 패키지 설치
sudo apt install -y python3 python3-pip git build-essential

# CUDA 설치 확인
nvidia-smi

Python 환경 설정

Conda 사용:

# 새 환경 생성
conda create -n vllm-env python=3.11 -y
conda activate vllm-env

# PyTorch 설치 (CUDA 버전에 맞게)
conda install pytorch torchvision torchaudio pytorch-cuda=12.1 -c pytorch -c nvidia

uv 사용 (권장):

# uv 설치
curl -LsSf https://astral.sh/uv/install.sh | sh

# 환경 생성 및 활성화
uv venv vllm-env --python 3.11 --seed
source vllm-env/bin/activate

vLLM 설치

기본 설치:

# pip 업그레이드
pip install --upgrade pip

# vLLM 설치
pip install vllm

Gemma 3 지원을 위한 설치:

# Transformers 최신 버전 설치 (Gemma 3 지원)
pip install git+https://github.com/huggingface/transformers@v4.49.0-Gemma-3

# vLLM 설치
pip install vllm

# 설치 확인
python -c "import vllm; print(vllm.__version__)"

Hugging Face 인증 설정

# Hugging Face CLI 설치
pip install huggingface_hub[cli]

# 로그인 (토큰 필요)
huggingface-cli login

# 또는 환경 변수로 설정
export HUGGING_FACE_HUB_TOKEN="your_token_here"

Gemma 3 27B 서버 실행

기본 서버 실행:

python -m vllm.entrypoints.openai.api_server \
  --model google/gemma-3-27b-it \
  --host 0.0.0.0 \
  --port 8000 \
  --tensor-parallel-size 1 \
  --max-model-len 4096 \
  --gpu-memory-utilization 0.9

멀티 GPU 환경:

python -m vllm.entrypoints.openai.api_server \
  --model google/gemma-3-27b-it \
  --host 0.0.0.0 \
  --port 8000 \
  --tensor-parallel-size 2 \
  --max-model-len 8192 \
  --gpu-memory-utilization 0.9

고급 설정:

python -m vllm.entrypoints.openai.api_server \
  --model google/gemma-3-27b-it \
  --host 0.0.0.0 \
  --port 8000 \
  --tensor-parallel-size 2 \
  --max-model-len 16384 \
  --max-num-batched-tokens 4096 \
  --max-num-seqs 32 \
  --gpu-memory-utilization 0.95 \
  --dtype float16 \
  --enable-chunked-prefill

API 사용 방법

텍스트 생성 (Completion):

curl http://localhost:8000/v1/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "google/gemma-3-27b-it",
    "prompt": "Python에서 머신러닝 모델을 훈련하는 방법:",
    "max_tokens": 500,
    "temperature": 0.7,
    "top_p": 0.9
  }'

채팅 API:

curl http://localhost:8000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "google/gemma-3-27b-it",
    "messages": [
      {
        "role": "user",
        "content": "한국어로 간단한 파이썬 스크립트를 작성해주세요"
      }
    ],
    "max_tokens": 1000,
    "temperature": 0.8
  }'

멀티모달 요청:

curl http://localhost:8000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "google/gemma-3-27b-it",
    "messages": [
      {
        "role": "user",
        "content": [
          {
            "type": "text",
            "text": "이 이미지를 한국어로 설명해주세요"
          },
          {
            "type": "image_url",
            "image_url": {
              "url": "https://example.com/image.jpg"
            }
          }
        ]
      }
    ]
  }'

Python 클라이언트 사용

from openai import OpenAI

# 클라이언트 설정
client = OpenAI(
    base_url="http://localhost:8000/v1",
    api_key="token-abc123"  # vLLM은 임의의 토큰 사용 가능
)

# 채팅 완성
response = client.chat.completions.create(
    model="google/gemma-3-27b-it",
    messages=[
        {"role": "system", "content": "당신은 한국어 전문 AI 어시스턴트입니다."},
        {"role": "user", "content": "딥러닝의 기본 개념을 설명해주세요."}
    ],
    temperature=0.7,
    max_tokens=1000
)

print(response.choices[0].message.content)

Docker를 이용한 vLLM 설치

Dockerfile 작성:

FROM vllm/vllm-openai:latest

# 환경 변수 설정
ENV HUGGING_FACE_HUB_TOKEN="your_token"
ENV MODEL_NAME="google/gemma-3-27b-it"

# 서버 실행 명령
CMD ["python", "-m", "vllm.entrypoints.openai.api_server", \
     "--model", "$MODEL_NAME", \
     "--host", "0.0.0.0", \
     "--port", "8000", \
     "--tensor-parallel-size", "1"]

Docker 실행:

# 이미지 빌드
docker build -t vllm-gemma3 .

# 컨테이너 실행
docker run --gpus all -p 8000:8000 \
  -e HUGGING_FACE_HUB_TOKEN="your_token" \
  vllm-gemma3

성능 최적화 및 비교

Ollama vs vLLM 성능 비교

측면 Ollama vLLM
설치 난이도 매우 쉬움 보통
처리 속도 보통 매우 빠름
메모리 효율 보통 우수
동시 요청 처리 제한적 뛰어남
API 호환성 자체 API OpenAI 호환
커스터마이징 제한적 광범위

vLLM 성능 튜닝

메모리 최적화:

# KV 캐시 최적화
--kv-cache-dtype fp8

# 양자화 적용
--quantization awq

# 청크 프리필 활성화
--enable-chunked-prefill

처리량 최적화:

# 배치 크기 조정
--max-num-batched-tokens 8192
--max-num-seqs 64

# 텐서 병렬화
--tensor-parallel-size 2
--pipeline-parallel-size 1

모니터링 및 로깅

# 상세 로깅 활성화
--log-level DEBUG

# Prometheus 메트릭 활성화
--disable-log-stats false

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

실제 활용 사례

개발 도구 통합

VS Code 확장 연동:

import requests

def code_completion(prompt):
    response = requests.post(
        "http://localhost:8000/v1/completions",
        json={
            "model": "google/gemma-3-27b-it",
            "prompt": f"# 코드 완성\n{prompt}",
            "max_tokens": 200,
            "temperature": 0.2,
            "stop": ["#", "\n\n"]
        }
    )
    return response.json()["choices"][0]["text"]

웹 애플리케이션 통합

FastAPI 서버:

from fastapi import FastAPI
import asyncio
import aiohttp

app = FastAPI()

@app.post("/chat")
async def chat(message: str):
    async with aiohttp.ClientSession() as session:
        async with session.post(
            "http://localhost:8000/v1/chat/completions",
            json={
                "model": "google/gemma-3-27b-it",
                "messages": [{"role": "user", "content": message}]
            }
        ) as response:
            result = await response.json()
            return {"reply": result["choices"][0]["message"]["content"]}

배치 처리 스크립트

import asyncio
import aiohttp
from typing import List

async def batch_process(prompts: List[str]):
    tasks = []
    
    async with aiohttp.ClientSession() as session:
        for prompt in prompts:
            task = session.post(
                "http://localhost:8000/v1/completions",
                json={
                    "model": "google/gemma-3-27b-it",
                    "prompt": prompt,
                    "max_tokens": 100
                }
            )
            tasks.append(task)
        
        responses = await asyncio.gather(*tasks)
        results = []
        
        for response in responses:
            result = await response.json()
            results.append(result["choices"][0]["text"])
        
        return results

# 사용 예시
prompts = [
    "Python 리스트 컴프리헨션이란?",
    "머신러닝의 기본 개념은?",
    "웹 개발에서 REST API란?"
]

results = asyncio.run(batch_process(prompts))

문제 해결 및 트러블슈팅

일반적인 문제들

CUDA 메모리 부족:

# GPU 메모리 사용량 줄이기
--gpu-memory-utilization 0.8
--max-model-len 2048

# 텐서 병렬화 증가
--tensor-parallel-size 2

모델 로딩 실패:

# Transformers 버전 확인
pip install git+https://github.com/huggingface/transformers@v4.49.0-Gemma-3

# 수동으로 모델 다운로드
huggingface-cli download google/gemma-3-27b-it

연결 타임아웃:

# 타임아웃 증가
--max-waiting-time 300

# 워커 수 조정
--worker-use-ray false

성능 문제 해결

느린 추론 속도:

  • --enable-chunked-prefill 활성화
  • --max-num-batched-tokens 값 증가
  • GPU 메모리 사용률 최적화

높은 지연시간:

  • 배치 크기 감소
  • --max-num-seqs 값 조정
  • 텐서 병렬화 최적화

메모리 최적화

# 양자화 적용
--quantization fp8

# KV 캐시 압축
--kv-cache-dtype fp8

# 모델 오프로딩
--cpu-offload-gb 4

프로덕션 배포 가이드

Kubernetes 배포

deployment.yaml:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: vllm-gemma3-deployment
spec:
  replicas: 1
  selector:
    matchLabels:
      app: vllm-gemma3
  template:
    metadata:
      labels:
        app: vllm-gemma3
    spec:
      containers:
      - name: vllm-server
        image: vllm/vllm-openai:latest
        resources:
          requests:
            nvidia.com/gpu: 2
            memory: "64Gi"
          limits:
            nvidia.com/gpu: 2
            memory: "64Gi"
        env:
        - name: HUGGING_FACE_HUB_TOKEN
          valueFrom:
            secretKeyRef:
              name: hf-secret
              key: token
        command:
        - python
        - -m
        - vllm.entrypoints.openai.api_server
        - --model=google/gemma-3-27b-it
        - --tensor-parallel-size=2
        - --host=0.0.0.0
        - --port=8000

로드 밸런싱

Nginx 설정:

upstream vllm_servers {
    server localhost:8000;
    server localhost:8001;
}

server {
    listen 80;
    location /v1/ {
        proxy_pass http://vllm_servers;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

모니터링 설정

Prometheus 구성:

scrape_configs:
  - job_name: 'vllm'
    static_configs:
      - targets: ['localhost:8000']
    metrics_path: '/metrics'

결론

Gemma 3 27B는 현재 단일 GPU에서 실행할 수 있는 최고 성능의 오픈소스 모델입니다. Ollama는 빠른 프로토타이핑과 개인 사용에 적합하며, vLLM은 프로덕션 환경에서 고성능 서빙이 필요한 경우에 최적의 선택입니다.

Ollama 추천 상황:

  • 개인 개발 및 학습
  • 빠른 프로토타이핑
  • 간단한 API 통합

vLLM 추천 상황:

  • 프로덕션 서비스
  • 고성능 추론 필요
  • 대량의 동시 요청 처리
  • 세밀한 성능 튜닝 요구

두 도구 모두 각각의 장점이 있으므로, 사용 목적에 맞는 도구를 선택하여 Gemma 3 27B의 강력한 성능을 최대한 활용해보시기 바랍니다. 로컬 AI의 새로운 시대를 함께 열어가세요!

Leave a Comment