ข้ามไปที่เนื้อหา

vLLM: ทำ LLM Serving ระดับ Production ตั้งแต่ศูนย์จนถึง Scale

คุณโหลด large language model มาแล้ว รันขึ้นแล้วด้วย แต่ใช้ไปสักพักก็เริ่มเห็นปัญหา ตอบช้า รับได้ทีละ request แถม GPU ยังทำงานไม่เต็มที่โดยไม่รู้สาเหตุ พอมีสองคนเรียกพร้อมกัน อีกคนก็ต้องนั่งรอ รอไปเรื่อยๆ

นี่แหละ ปัญหา LLM serving และ vLLM คือ open-source ที่คนเลือกใช้แก้ปัญหานี้มากที่สุด


Part 1: vLLM เข้ามาแก้ปัญหาอะไร

ทำไม LLM Serving แบบ Naïve ถึงช้า

เวลาเรียก model.generate(...) ตรงๆ เบื้องหลังมีอยู่สามเรื่องที่ทำให้ serve ผู้ใช้หลายคนพร้อมกันไม่ไหว

ปัญหาที่ 1: จอง KV Cache แบบ Static จน Memory เหลือทิ้ง

ทุกครั้งที่ model อ่าน input token ก็ต้องคำนวณ Key-Value (KV) tensor ให้ attention ใช้ tensor ชุดนี้ใหญ่ และต้องอยู่ใน GPU memory ไปจนกว่าจะ generate เสร็จ

A request with 512 token context on a 7B model:
  KV cache size = 2 × num_layers × num_heads × head_dim × seq_len × dtype_bytes
                = 2 × 32 × 32 × 128 × 512 × 2 bytes
                = ~268 MB per request

If you pre-allocate for the maximum sequence length (4096):
  268 MB × (4096/512) = 2.1 GB — even if the actual output is 50 tokens!

Framework แบบ naïve จองเผื่อ memory ไว้เต็มเพดานตั้งแต่แรก ทั้งที่ส่วนใหญ่ไม่ได้ใช้ เลยว่างทิ้งไว้เฉยๆ

ปัญหาที่ 2: รับหลาย Request พร้อมกันไม่ได้

Inference แบบปกติทำทีละ request ต้องรอ request 1 เสร็จก่อนถึงจะเริ่ม request 2 แล้วค่อยต่อด้วย request 3

Naïve server:
  Time →
  GPU:  [===Req1===][===Req2===][===Req3===]
         40s         40s         40s         Total: 120s
         User 1 OK   User 2 waits 40s   User 3 waits 80s

ระหว่างที่รอ batch ของ token ถัดไป GPU ก็ว่างงานไปบางส่วน

ปัญหาที่ 3: Memory Fragmentation

ต่อให้ batch request รวมกัน แต่ละ request ก็ยาวไม่เท่ากันอยู่ดี memory ที่จองไว้ให้ request ยาวหนึ่งตัว จะแบ่งให้ request สั้นสามตัวใช้ก็ไม่ได้

GPU Memory (24 GB):
  [====Request A (2048 max)====][====Request B (2048 max)====][  12 GB free  ]
  ^^ But Request A only uses 200 tokens! 1.8 GB wasted ^^

vLLM ทำได้แค่ไหน

vLLM แก้ครบทั้งสามข้อ ผลที่ได้ออกมาแบบนี้

Metric Naïve serving vLLM
Throughput 1–3 req/s (7B) 20–50+ req/s (7B)
GPU Memory Efficiency ใช้จริง 40–60% ใช้จริง 90–95%
ผู้ใช้พร้อมกัน 1 หลายร้อย
Latency (first token) เท่าเดิม เท่าเดิมหรือเร็วกว่า
Latency (full response) Baseline throughput ดีขึ้น 10–24×

Part 2: เบื้องหลัง vLLM — ไอเดียหลักสี่ข้อ

ไอเดียที่ 1: PagedAttention

PagedAttention คือจุดขายหลักของ vLLM มาจากเปเปอร์ของ UC Berkeley ปี 2023 ไอเดียยืมมาจาก operating system ตรงๆ คือ virtual memory paging

OS ทั่วไปแบ่ง RAM จริงเป็น page ขนาดเท่ากัน memory ของโปรแกรมไม่จำเป็นต้องอยู่ติดกัน กระจายไปอยู่ตาม page ไหนก็ได้ แล้วใช้ page table จับคู่ virtual address กับ physical page แค่นี้ fragmentation ก็หายไป

PagedAttention เอาวิธีเดียวกันมาใช้กับ KV cache

Traditional KV Cache (pre-vLLM):
  GPU Memory:
  ┌──────────────────────────────────────────────────────┐
  │ Request A: [tok0][tok1][tok2][EMPTY][EMPTY][EMPTY]   │ ← 50% wasted
  │ Request B: [tok0][tok1][EMPTY][EMPTY][EMPTY][EMPTY]  │ ← 67% wasted
  │ Request C: NO ROOM — must wait                       │
  └──────────────────────────────────────────────────────┘

PagedAttention KV Cache:
  GPU Memory divided into fixed-size BLOCKS (e.g., 16 tokens each):
  ┌────┬────┬────┬────┬────┬────┬────┬────┬────┬────┐
  │ B0 │ B1 │ B2 │ B3 │ B4 │ B5 │ B6 │ B7 │ B8 │ B9 │
  └────┴────┴────┴────┴────┴────┴────┴────┴────┴────┘

  Request A uses blocks: B0, B2, B7        (only what it needs)
  Request B uses blocks: B1, B4            (only what it needs)
  Request C uses blocks: B3, B5, B8, B9   (fits in the gaps!)

  Block table maps logical blocks to physical blocks:
  Request A → [B0 at pos 0, B2 at pos 1, B7 at pos 2]

ได้อะไร: - Internal fragmentation แทบไม่มี (เสียไม่ถึง 4% ต่อ block) - Request ที่ขึ้นต้นด้วย prefix เดียวกันแชร์ block กันได้ (prompt caching) - พอมี block ว่าง request ใหม่ก็เริ่มได้เลย

ไอเดียที่ 2: Continuous Batching

Batching แบบ naïve ต้องรอทุก request ใน batch เสร็จก่อน ถึงจะรับ request ใหม่ได้ แต่แต่ละ request จบไม่พร้อมกัน เลยเสียเวลาไปเปล่าๆ

Static batching:
  Batch 1: [Req A ===30tok===][Req B ======50tok======]
  Batch 2: starts only after BOTH A and B finish (50 tok wait)
  GPU idle during last 20 tokens of B waiting for A!

Continuous batching (vLLM):
  Iteration 0: [A][B][C]
  Iteration 1: [A][B][C]
  ...
  Iteration 30: [A finishes][B][C]  → immediately swap in [D]!
  Iteration 31: [D][B][C]           ← no gap
  ...
  GPU is always doing useful work

บางคนเรียกวิธีนี้ว่า "iteration-level scheduling" คือ scheduler ตัดสินใจใหม่ทุก step ที่ generate token ไม่ได้รอตัดสินใจทีละ batch

ไอเดียที่ 3: Prefix Caching (Prompt Caching)

ถ้าหลาย request ใช้ system prompt หรือ context ชุดเดียวกัน vLLM จะ cache KV block ของ prefix ส่วนนั้นไว้ แล้วใช้ซ้ำได้ทุก request ไม่ต้องคำนวณใหม่

System prompt: "You are a helpful customer service agent for AcmeCorp..."
              [=============== 500 tokens ===============]

Request 1: [shared prefix 500 tok] + "What are your hours?"
Request 2: [shared prefix 500 tok] + "How do I return a product?"
Request 3: [shared prefix 500 tok] + "Where is my order?"

Without prefix caching: compute 500-token prefix 3 times
With prefix caching:    compute 500-token prefix ONCE, reuse KV cache
Speedup: ~35% for typical RAG/chat applications

ไอเดียที่ 4: Speculative Decoding

Speculative decoding ให้ model "draft" ตัวเล็กเดา candidate token ล่วงหน้าทีละหลายตัวแบบเร็วๆ แล้วให้ model ตัวใหญ่ตรวจทีเดียวพร้อมกัน

Normal generation (LLaMA 70B):
  Generate token 1 → Generate token 2 → Generate token 3 ...
  Each step: full 70B forward pass

Speculative decoding:
  Draft model (1B) generates 5 candidate tokens: ["The", "cat", "sat", "on", "the"]
  Large model (70B) verifies all 5 in ONE forward pass
  Accept tokens up to first mismatch, reject rest, continue

  Result: 2–4× more tokens per second for easy/predictable text

Part 3: ติดตั้งและเริ่มใช้งาน

ต้องมีอะไรบ้าง

Requirement ขั้นต่ำ แนะนำ
GPU NVIDIA (CUDA 11.8+) NVIDIA (CUDA 12.x)
VRAM 8 GB (7B model ที่ fp16... เบียดมาก) 24 GB (7B สบายๆ), 80 GB (70B)
RAM 32 GB 64 GB+
Python 3.9 3.11+
OS Linux Linux (Ubuntu 22.04)
Driver CUDA 11.8 CUDA 12.4+

VRAM ต้องมีเท่าไหร่

vLLM โหลด model weight ทั้งก้อนขึ้น GPU VRAM model 7B parameter ที่ float16 กิน VRAM ราว 14 GB แค่ weight อย่างเดียว ยังไม่นับ KV cache ที่ต้องเผื่อเพิ่ม คร่าวๆ ให้เตรียมไว้แบบนี้

  • 7B model → GPU 16–24 GB (RTX 4090, A10G, L4)
  • 13B model → GPU 28–40 GB (A100 40GB)
  • 70B model → 2× A100 80GB หรือ 4× A10G

ติดตั้ง

# Create a virtual environment first
python -m venv vllm-env
source vllm-env/bin/activate

# Install vLLM (CUDA 12.1 build)
pip install vllm

# Verify installation
python -c "import vllm; print(vllm.__version__)"
# If you have CUDA 11.8 (older systems)
pip install vllm --extra-index-url https://download.pytorch.org/whl/cu118
# Official vLLM Docker image — no dependency headaches
docker pull vllm/vllm-openai:latest

# Run with GPU access
docker run --runtime nvidia --gpus all \
    -v ~/.cache/huggingface:/root/.cache/huggingface \
    -p 8000:8000 \
    vllm/vllm-openai:latest \
    --model meta-llama/Meta-Llama-3-8B-Instruct
# uv is much faster than pip for installing large packages
uv venv vllm-env
source vllm-env/bin/activate
uv pip install vllm

ลองรัน Inference ครั้งแรก

# hello_vllm.py
from vllm import LLM, SamplingParams

# Load model — this downloads from HuggingFace on first run
# (set HF_TOKEN env var for gated models like LLaMA)
llm = LLM(model="Qwen/Qwen2.5-7B-Instruct")

# Sampling parameters
params = SamplingParams(
    temperature=0.7,
    top_p=0.9,
    max_tokens=256
)

# Generate — notice we pass a LIST of prompts (batching!)
prompts = [
    "What is PagedAttention in vLLM?",
    "Write a Python function to check if a number is prime.",
    "Explain the concept of entropy in information theory.",
]

outputs = llm.generate(prompts, params)

for output in outputs:
    prompt = output.prompt
    response = output.outputs[0].text
    print(f"Prompt: {prompt!r}")
    print(f"Response: {response}")
    print("─" * 60)

รันได้เลย

python hello_vllm.py

จะเห็นว่า vLLM ประมวลผลทั้งสาม prompt ใน batch เดียว เร็วกว่าเรียก generate แยกสามรอบเยอะ


Part 4: OpenAI-Compatible Server

สำหรับทีมส่วนใหญ่ ฟีเจอร์นี้คือเหตุผลหลักที่เลือก vLLM vLLM เปิด REST API ที่หน้าตาเหมือน OpenAI เพราะฉะนั้น tool หรือ SDK ที่ใช้อยู่แล้ว แค่ชี้มาที่ vLLM server ก็ใช้ได้ทันที ไม่ต้องแก้โค้ดสักบรรทัด

เปิด Server

# Basic startup
python -m vllm.entrypoints.openai.api_server \
    --model meta-llama/Meta-Llama-3-8B-Instruct \
    --host 0.0.0.0 \
    --port 8000

# With common options
python -m vllm.entrypoints.openai.api_server \
    --model meta-llama/Meta-Llama-3-8B-Instruct \
    --host 0.0.0.0 \
    --port 8000 \
    --max-model-len 8192 \          # context window
    --tensor-parallel-size 2 \      # use 2 GPUs
    --gpu-memory-utilization 0.90 \ # use 90% of GPU VRAM
    --enable-prefix-caching \       # enable prompt caching
    --served-model-name "my-llama" # custom model name for API

เรียกจาก Python

from openai import OpenAI

# Point to your vLLM server instead of api.openai.com
client = OpenAI(
    base_url="http://localhost:8000/v1",
    api_key="not-needed"  # vLLM doesn't require a key by default
)

# Chat completions — identical to calling OpenAI API
response = client.chat.completions.create(
    model="meta-llama/Meta-Llama-3-8B-Instruct",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "What is the capital of Thailand?"}
    ],
    temperature=0.7,
    max_tokens=200
)

print(response.choices[0].message.content)
print(f"Usage: {response.usage}")
from openai import OpenAI

client = OpenAI(base_url="http://localhost:8000/v1", api_key="not-needed")

# Stream the response token by token
stream = client.chat.completions.create(
    model="meta-llama/Meta-Llama-3-8B-Instruct",
    messages=[{"role": "user", "content": "Tell me a short story."}],
    stream=True  # ← enable streaming
)

for chunk in stream:
    delta = chunk.choices[0].delta
    if delta.content:
        print(delta.content, end="", flush=True)
print()  # newline at end
curl http://localhost:8000/v1/chat/completions \
    -H "Content-Type: application/json" \
    -d '{
        "model": "meta-llama/Meta-Llama-3-8B-Instruct",
        "messages": [
            {"role": "user", "content": "What is vLLM?"}
        ],
        "temperature": 0.7,
        "max_tokens": 200
    }'
import asyncio
import httpx

async def chat(prompt: str) -> str:
    async with httpx.AsyncClient() as client:
        response = await client.post(
            "http://localhost:8000/v1/chat/completions",
            json={
                "model": "meta-llama/Meta-Llama-3-8B-Instruct",
                "messages": [{"role": "user", "content": prompt}],
                "max_tokens": 300,
            },
            timeout=60.0
        )
        return response.json()["choices"][0]["message"]["content"]

async def main():
    # Run 5 requests concurrently — vLLM handles them all
    results = await asyncio.gather(*[
        chat(f"Question {i}: What is {topic}?")
        for i, topic in enumerate(["Python", "Kubernetes", "vLLM", "LLM", "DevOps"])
    ])
    for r in results:
        print(r[:100], "...\n")

asyncio.run(main())

เช็ก Health ของ Server และดู Model ที่มี

# List available models
curl http://localhost:8000/v1/models | python -m json.tool

# Health check
curl http://localhost:8000/health

# Server metrics (Prometheus format)
curl http://localhost:8000/metrics

Part 5: Configuration Option ที่ควรรู้

ทุก configuration flag ส่งผลกับ quality, speed หรือ memory สักทาง รู้ trade-off ของแต่ละตัวแล้วจะจูนให้เข้ากับ workload ได้ง่ายขึ้น

GPU Memory Utilization

--gpu-memory-utilization 0.90  # default: 0.90

ตัวนี้กำหนดว่า vLLM จะกัน GPU VRAM ไว้ให้ KV cache กี่เปอร์เซ็นต์ ที่เหลือเป็นที่ของ model weight

GPU VRAM = 24 GB
Model weights (7B fp16) ≈ 14 GB

With --gpu-memory-utilization 0.90:
  Reserved = 24 × 0.90 = 21.6 GB
  KV cache = 21.6 - 14 = 7.6 GB → supports ~180 concurrent 512-token requests

With --gpu-memory-utilization 0.70:
  Reserved = 24 × 0.70 = 16.8 GB
  KV cache = 16.8 - 14 = 2.8 GB → supports ~66 concurrent requests

If you see OOM errors → lower this value
If you want more concurrent users → raise this value (carefully)

Max Model Length

--max-model-len 4096  # limit context window

Context window เล็กลง KV cache สูงสุดก็เล็กลง รับ request พร้อมกันได้มากขึ้น

If your users never need more than 4K tokens context:
  Setting --max-model-len 4096 on a model that supports 128K
  means the KV cache is sized for 4K, not 128K
  → 32× more efficient use of KV cache memory!

Tensor Parallelism (Multi-GPU)

--tensor-parallel-size 2  # split model across 2 GPUs
--tensor-parallel-size 4  # split across 4 GPUs

Tensor parallelism หั่น weight matrix ของ model กระจายไปหลาย GPU แต่ละ GPU ถือ shard ของทุก layer ไว้ แล้วคุยกันผ่าน NVLink หรือ PCIe

Single GPU (A100 80GB): Can serve LLaMA 70B with tight KV cache
2× GPU (A100 80GB):     Comfortable 70B, large KV cache, faster
4× GPU (A100 80GB):     Even faster, large context windows (128K+)
8× GPU (A100 80GB):     405B models

ใช้ tensor parallelism ตอนไหน

  • Model ใส่ GPU ตัวเดียวไม่พอ → ใช้ TP
  • Model ใส่ได้ แต่อยากได้ throughput เพิ่ม → ลอง data parallelism (รัน server หลาย instance) ก่อน overhead น้อยกว่า TP

ถ้าอยากได้ decision tree ครบๆ ทั้ง TP vs PP vs DP, ต้นทุน AllReduce ในแต่ละ layer, การตั้ง Ray แบบ multi-node และ Expert Parallelism สำหรับ MoE model ไปอ่านต่อได้ที่ Scaling LLM Inference: DP, PP และ TP

Quantization

Quantization ลด precision ของ model ลง ใช้ memory น้อยลงและรันเร็วขึ้น

# Use a pre-quantized model from HuggingFace
python -m vllm.entrypoints.openai.api_server \
    --model Qwen/Qwen2.5-7B-Instruct-AWQ \
    --quantization awq

AWQ (Activation-aware Weight Quantization) quantize ลงเหลือ 4-bit โดย accuracy ตกน้อยมาก model 7B แบบ AWQ ใช้ VRAM แค่ ~4 GB จากเดิม ~14 GB

python -m vllm.entrypoints.openai.api_server \
    --model TheBloke/Llama-2-7B-chat-GPTQ \
    --quantization gptq
# FP8 is fastest on Hopper GPUs (H100, H200)
python -m vllm.entrypoints.openai.api_server \
    --model meta-llama/Meta-Llama-3-8B-Instruct \
    --quantization fp8
# Load any model in 4-bit or 8-bit on the fly (no pre-quantized model needed)
llm = LLM(
    model="meta-llama/Meta-Llama-3-70B-Instruct",
    quantization="bitsandbytes",
    load_format="bitsandbytes"
)

เทียบ Quantization แต่ละแบบ:

วิธี Bits Quality ที่เสียไป VRAM เทียบกับ FP16 Speed
FP16 16 ไม่เสีย (baseline) 1× Baseline
BF16 16 ไม่เสีย 1× เท่าเดิม
FP8 8 น้อยมาก 0.5× เร็วขึ้น 1.5–2×
GPTQ 4 เล็กน้อย 0.25× เร็วขึ้น 1.2×
AWQ 4 น้อยมาก (calibrate ได้ดีกว่า) 0.25× เร็วขึ้น 1.2×

เจาะลึก Sampling Parameters

from vllm import SamplingParams

params = SamplingParams(
    # Core sampling
    temperature=0.7,      # 0 = deterministic, >1 = more random
    top_p=0.9,           # nucleus sampling: top tokens summing to 90% probability
    top_k=50,            # only consider top 50 tokens

    # Length control
    max_tokens=512,       # maximum tokens to generate
    min_tokens=10,        # minimum before EOS is allowed

    # Repetition control
    presence_penalty=0.1, # penalize tokens that already appeared
    frequency_penalty=0.1,# penalize tokens proportional to how often they appeared
    repetition_penalty=1.1,# multiplicative penalty (>1 reduces repetition)

    # Stopping conditions
    stop=["<|eot_id|>", "Human:", "User:"],  # stop on these strings
    stop_token_ids=[128009],                  # stop on these token IDs

    # Multiple outputs
    n=3,                  # generate 3 different completions
    best_of=5,           # generate 5 internally, return the 3 highest-scoring

    # Determinism
    seed=42,             # for reproducible outputs
)

Part 6: Deploy จริงทำได้กี่แบบ

Pattern 1: Deploy ด้วย Docker แบบง่ายๆ

# docker-compose.yml
version: "3.8"
services:
  vllm:
    image: vllm/vllm-openai:latest
    runtime: nvidia
    environment:
      - NVIDIA_VISIBLE_DEVICES=all
      - HF_TOKEN=${HF_TOKEN}  # for gated models like LLaMA
      - HF_HOME=/cache/huggingface
    volumes:
      - huggingface-cache:/cache/huggingface
    ports:
      - "8000:8000"
    command: >
      --model meta-llama/Meta-Llama-3-8B-Instruct
      --host 0.0.0.0
      --port 8000
      --max-model-len 8192
      --gpu-memory-utilization 0.90
      --enable-prefix-caching
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:8000/health"]
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 120s  # model loading takes time!

volumes:
  huggingface-cache:
# Start
HF_TOKEN=your_token docker compose up -d

# Check logs
docker compose logs -f vllm

# Test
curl http://localhost:8000/v1/models

Pattern 2: Deploy บน Kubernetes

# vllm-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: vllm-server
  namespace: ai
spec:
  replicas: 1  # scale based on load
  selector:
    matchLabels:
      app: vllm-server
  template:
    metadata:
      labels:
        app: vllm-server
    spec:
      containers:
      - name: vllm
        image: vllm/vllm-openai:latest
        args:
        - "--model"
        - "meta-llama/Meta-Llama-3-8B-Instruct"
        - "--host"
        - "0.0.0.0"
        - "--port"
        - "8000"
        - "--gpu-memory-utilization"
        - "0.90"
        - "--enable-prefix-caching"
        ports:
        - containerPort: 8000
        env:
        - name: HF_TOKEN
          valueFrom:
            secretKeyRef:
              name: hf-credentials
              key: token
        resources:
          requests:
            nvidia.com/gpu: "1"
            memory: "32Gi"
            cpu: "4"
          limits:
            nvidia.com/gpu: "1"
            memory: "48Gi"
            cpu: "8"
        readinessProbe:
          httpGet:
            path: /health
            port: 8000
          initialDelaySeconds: 120
          periodSeconds: 10
        livenessProbe:
          httpGet:
            path: /health
            port: 8000
          initialDelaySeconds: 180
          periodSeconds: 30
        volumeMounts:
        - name: hf-cache
          mountPath: /root/.cache/huggingface
      volumes:
      - name: hf-cache
        persistentVolumeClaim:
          claimName: hf-model-cache
      nodeSelector:
        accelerator: nvidia-a10g  # schedule on GPU nodes
      tolerations:
      - key: nvidia.com/gpu
        operator: Exists
        effect: NoSchedule
---
apiVersion: v1
kind: Service
metadata:
  name: vllm-service
  namespace: ai
spec:
  selector:
    app: vllm-server
  ports:
  - port: 80
    targetPort: 8000
  type: ClusterIP

Pattern 3: หลาย Model หลัง Router ตัวเดียว

ถ้าต้อง serve หลาย model ให้วาง router เบาๆ (เช่น LiteLLM) ไว้หน้า vLLM ทุก instance

# litellm-config.yaml
model_list:
  - model_name: "fast-model"      # alias exposed to clients
    litellm_params:
      model: openai/meta-llama/Meta-Llama-3-8B-Instruct
      api_base: http://vllm-8b:8000/v1
      api_key: not-needed

  - model_name: "smart-model"
    litellm_params:
      model: openai/meta-llama/Meta-Llama-3-70B-Instruct
      api_base: http://vllm-70b:8000/v1
      api_key: not-needed

  - model_name: "code-model"
    litellm_params:
      model: openai/Qwen/Qwen2.5-Coder-32B-Instruct
      api_base: http://vllm-coder:8000/v1
      api_key: not-needed

router_settings:
  routing_strategy: "least-busy"  # route to least loaded instance
  fallbacks:
    - {"smart-model": ["fast-model"]}  # fallback if 70B is overloaded
# Run the router
litellm --config litellm-config.yaml --port 4000

จากนี้ client แค่คุยกับ http://localhost:4000/v1 แล้วระบุชื่อ model ที่อยากใช้ เรื่อง load balancing กับ fallback ปล่อยให้ router จัดการ

Pattern 4: เพิ่ม Authentication

ค่า default ของ vLLM ไม่มี authentication เลย ถ้าจะขึ้น production ให้ทำแบบนี้

# auth_proxy.py — simple FastAPI proxy with API key auth
from fastapi import FastAPI, HTTPException, Depends, Request
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
import httpx

app = FastAPI()
security = HTTPBearer()

VALID_KEYS = {"sk-user1-key-here", "sk-user2-key-here"}
VLLM_BASE = "http://localhost:8000"

def verify_key(credentials: HTTPAuthorizationCredentials = Depends(security)):
    if credentials.credentials not in VALID_KEYS:
        raise HTTPException(status_code=401, detail="Invalid API key")

@app.api_route("/{path:path}", methods=["GET", "POST", "DELETE"])
async def proxy(request: Request, path: str, _=Depends(verify_key)):
    async with httpx.AsyncClient() as client:
        response = await client.request(
            method=request.method,
            url=f"{VLLM_BASE}/{path}",
            content=await request.body(),
            headers={k: v for k, v in request.headers.items()
                     if k.lower() not in ("host", "authorization")},
            timeout=300.0,
        )
    return response.json()

ใน production จริงควรใช้ของที่ทำมาเพื่องานนี้ เช่น LiteLLM Proxy (มี auth, rate limiting และ budget management ในตัว) หรือวาง Kong / Nginx ไว้ด้านหน้า


Part 7: ฟีเจอร์ขั้นสูง

Structured Output (JSON Mode)

บังคับให้ model ตอบเป็น JSON ที่ valid และตรง schema เรื่องนี้สำคัญมากถ้าเอาไปใช้ในแอป production

from vllm import LLM, SamplingParams
from vllm.sampling_params import GuidedDecodingParams

llm = LLM(model="Qwen/Qwen2.5-7B-Instruct")

# Define the schema you want
product_schema = {
    "type": "object",
    "properties": {
        "name": {"type": "string"},
        "price": {"type": "number"},
        "in_stock": {"type": "boolean"},
        "tags": {
            "type": "array",
            "items": {"type": "string"}
        }
    },
    "required": ["name", "price", "in_stock"]
}

params = SamplingParams(
    temperature=0.1,
    max_tokens=200,
    guided_decoding=GuidedDecodingParams(json=product_schema)
)

output = llm.generate(
    ["Extract product info: 'The Nike Air Max 90 costs $150 and is available in stores. Tags: shoes, running, nike'"],
    params
)

import json
result = json.loads(output[0].outputs[0].text)
print(result)
# {"name": "Nike Air Max 90", "price": 150.0, "in_stock": true, "tags": ["shoes", "running", "nike"]}

หรือจะเรียกผ่าน OpenAI-compatible API ก็ได้

from openai import OpenAI
from pydantic import BaseModel

client = OpenAI(base_url="http://localhost:8000/v1", api_key="not-needed")

class Product(BaseModel):
    name: str
    price: float
    in_stock: bool
    tags: list[str]

response = client.beta.chat.completions.parse(
    model="Qwen/Qwen2.5-7B-Instruct",
    messages=[
        {"role": "user",
         "content": "Extract: 'The Nike Air Max 90 costs $150 and is available.'"}
    ],
    response_format=Product,
)

product = response.choices[0].message.parsed
print(f"{product.name}: ${product.price}")

Tool Calling / Function Calling

from openai import OpenAI
import json

client = OpenAI(base_url="http://localhost:8000/v1", api_key="not-needed")

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get current weather for a city",
            "parameters": {
                "type": "object",
                "properties": {
                    "city": {"type": "string", "description": "City name"},
                    "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
                },
                "required": ["city"]
            }
        }
    }
]

response = client.chat.completions.create(
    model="meta-llama/Meta-Llama-3-8B-Instruct",
    messages=[{"role": "user", "content": "What's the weather in Bangkok?"}],
    tools=tools,
    tool_choice="auto"
)

# Check if the model called a tool
message = response.choices[0].message
if message.tool_calls:
    tool_call = message.tool_calls[0]
    function_name = tool_call.function.name
    function_args = json.loads(tool_call.function.arguments)
    print(f"Model called: {function_name}({function_args})")
    # → Model called: get_weather({"city": "Bangkok", "unit": "celsius"})

Serve LoRA Adapter

LoRA (Low-Rank Adaptation) ใช้ fine-tune model ด้วยข้อมูลของเราเองโดยแทบไม่กิน compute ส่วน vLLM ก็ serve LoRA adapter หลายตัวบน base model ตัวเดียวได้

# Start server with LoRA support
python -m vllm.entrypoints.openai.api_server \
    --model meta-llama/Meta-Llama-3-8B-Instruct \
    --enable-lora \
    --max-loras 4 \                    # max adapters loaded simultaneously
    --max-lora-rank 64 \               # max LoRA rank to support
    --lora-modules \
        customer-service=/path/to/cs-lora \
        legal-qa=/path/to/legal-lora \
        coding=/path/to/coding-lora

เรียก adapter ตัวที่ต้องการ

# Use the customer-service LoRA adapter
response = client.chat.completions.create(
    model="customer-service",  # ← adapter name, not base model
    messages=[{"role": "user", "content": "How do I return a product?"}]
)

วิธีนี้คุ้มมาก GPU ตัวเดียวรัน base model ตัวเดียว แต่ serve ได้หลาย variant ที่ fine-tune ให้เก่งคนละด้าน


Part 8: Monitoring และ Performance Tuning

Prometheus Metrics มีให้ในตัว

vLLM เปิด metrics ไว้ที่ /metrics

curl http://localhost:8000/metrics

Metrics ที่ควรจับตาดู

# Request metrics
vllm:request_success_total           # successful requests
vllm:request_prompt_tokens_total     # input tokens processed
vllm:request_generation_tokens_total # output tokens generated
vllm:e2e_request_latency_seconds     # end-to-end latency histogram
vllm:time_to_first_token_seconds     # latency to first token (TTFT)
vllm:time_per_output_token_seconds   # inter-token latency (ITL)

# System metrics
vllm:gpu_cache_usage_perc            # KV cache utilization (aim for 70-90%)
vllm:num_requests_running            # currently being processed
vllm:num_requests_waiting            # queued, waiting for KV cache space
vllm:num_requests_swapped            # swapped to CPU (bad — means OOM pressure)

Grafana dashboard — import dashboard ที่ community ทำไว้ได้จาก grafana.com/grafana/dashboards/?search=vllm

ตั้ง Prometheus + Grafana

# prometheus.yml
global:
  scrape_interval: 15s

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

Performance Benchmarking

vLLM มี benchmarking tool แถมมาให้

# Benchmark throughput
python -m vllm.entrypoints.openai.run_bench_throughput \
    --backend openai-chat \
    --base-url http://localhost:8000 \
    --model meta-llama/Meta-Llama-3-8B-Instruct \
    --dataset-name sharegpt \
    --dataset-path ShareGPT_V3_unfiltered_cleaned_split.json \
    --num-prompts 1000 \
    --request-rate 10   # requests per second

# Benchmark latency
python -m vllm.entrypoints.openai.run_bench_latency \
    --backend openai-chat \
    --base-url http://localhost:8000 \
    --model meta-llama/Meta-Llama-3-8B-Instruct \
    --num-prompts 100 \
    --input-len 512 \
    --output-len 128

ผลที่ควรได้บน A10G (24 GB) กับ LLaMA 3 8B:

Throughput benchmark:
  Total time: 52.3 s
  Throughput: 19.12 requests/s
  Output token throughput: 2,547 tokens/s

Latency benchmark (p50/p90/p99):
  Time to first token:  45ms / 89ms / 234ms
  Inter-token latency:  12ms / 15ms / 21ms
  End-to-end latency:  1.2s / 2.3s / 4.1s (for 128 output tokens)

Checklist สำหรับจูน Performance

GPU Utilization (aim for >85%):
  ☐ Use --gpu-memory-utilization 0.90 (or 0.95 if stable)
  ☐ Enable prefix caching: --enable-prefix-caching
  ☐ Use chunked prefill: --enable-chunked-prefill
  ☐ Tune --max-num-seqs (default 256) for your concurrency needs

Memory Efficiency:
  ☐ Set --max-model-len to actual maximum you need (not model's max)
  ☐ Use quantization (AWQ/GPTQ) if VRAM is constrained
  ☐ Use --cpu-offload-gb to spill KV cache to RAM (last resort)

Throughput:
  ☐ Send requests in batches when possible (offline scenarios)
  ☐ Use --max-num-batched-tokens to control memory per iteration
  ☐ Enable speculative decoding for predictable text workloads

Latency (interactive use):
  ☐ Use streaming (stream=True) so users see first tokens fast
  ☐ Preload the model (warmup) with a dummy request at startup
  ☐ Use smaller model with quantization for lowest latency
  ☐ Consider --preemption-mode abort vs recompute tradeoff

Part 9: เลือก Setup ตาม Use Case

Use Case Matrix

สถานการณ์ Setup ที่แนะนำ Flag หลัก
Local development GPU ตัวเดียว ไม่ต้องเปิด server เรียก class LLM() ตรงๆ ใน Python
API ใช้กันในทีม (< 10 users) OpenAI server + 1 GPU --max-model-len 4096
Production (หลักร้อย users) Docker/K8s + monitoring --enable-prefix-caching --tensor-parallel-size N
งบจำกัด Quantized model (AWQ) --quantization awq + model ที่เล็กลง
ต้องการ latency ต่ำ Speculative decoding --speculative-model
มีหลาย fine-tuned variant LoRA serving --enable-lora --lora-modules ...
Structured output (JSON) Guided decoding guided_decoding=GuidedDecodingParams(json=...)
Context ยาวมาก (100K+) Multi-GPU --tensor-parallel-size 4 --max-model-len 131072

เลือก Model ยังไงดี

For BEST quality (if GPU budget allows):
  70B model + vLLM → near-GPT-4 quality for most tasks

For BEST throughput per dollar:
  8B AWQ model → 4× the throughput of 8B fp16 at same quality loss

For LOWEST latency:
  3B–7B model with speculative decoding

For CODE generation:
  Qwen2.5-Coder-32B-Instruct or DeepSeek-Coder-V2

For MULTILINGUAL (including Thai):
  Qwen2.5-72B-Instruct (excellent multilingual support)
  SeaLLM for Southeast Asian languages specifically

For STRUCTURED output heavy workloads:
  Models fine-tuned on instruction following + JSON:
  Hermes-3-Llama-3.1-8B, Nous-Hermes-2-Mixtral

ประเมินค่าใช้จ่าย

# Quick cost calculator for self-hosted vLLM
def estimate_monthly_cost(
    requests_per_day: int,
    avg_input_tokens: int,
    avg_output_tokens: int,
    gpu_cost_per_hour: float,  # e.g., $2.50/hr for A10G on AWS
    throughput_tokens_per_sec: float  # from your benchmark
) -> dict:

    tokens_per_day = requests_per_day * (avg_input_tokens + avg_output_tokens)
    tokens_per_month = tokens_per_day * 30

    # GPU hours needed
    seconds_needed_per_day = (requests_per_day * avg_output_tokens) / throughput_tokens_per_sec
    gpu_hours_per_day = seconds_needed_per_day / 3600
    gpu_hours_per_month = gpu_hours_per_day * 30

    # Assume 24/7 instance (always-on for availability)
    monthly_cost_always_on = 24 * 30 * gpu_cost_per_hour

    # Equivalent OpenAI cost (GPT-4o: $5/1M input, $15/1M output)
    openai_cost = (
        (tokens_per_month / 1_000_000 * 5)    # input
        + (tokens_per_month * avg_output_tokens / (avg_input_tokens + avg_output_tokens) / 1_000_000 * 15)  # output
    )

    return {
        "tokens_per_month": f"{tokens_per_month:,}",
        "gpu_hours_if_scaled": f"{gpu_hours_per_month:.0f} hours",
        "monthly_cost_always_on": f"${monthly_cost_always_on:.0f}",
        "openai_equivalent_cost": f"${openai_cost:.0f}",
        "savings_vs_openai": f"${openai_cost - monthly_cost_always_on:.0f}"
    }

# Example: 10,000 requests/day, 500 input tokens, 300 output tokens
# A10G at $2.50/hr, throughput 2,000 tokens/sec
result = estimate_monthly_cost(
    requests_per_day=10_000,
    avg_input_tokens=500,
    avg_output_tokens=300,
    gpu_cost_per_hour=2.50,
    throughput_tokens_per_sec=2000
)
for k, v in result.items():
    print(f"{k}: {v}")
tokens_per_month: 240,000,000
gpu_hours_if_scaled: 450 hours
monthly_cost_always_on: $1,800
openai_equivalent_cost: $4,500
savings_vs_openai: $2,700

ปัญหาที่เจอบ่อยและวิธีเลี่ยง

ปัญหา อาการ วิธีแก้
Memory ไม่พอตั้งแต่ startup CUDA OOM ตอนโหลด model ใช้ quantization หรือ --tensor-parallel-size 2
OOM ระหว่าง inference CUDA OOM ตอนโหลดหนัก ลด --gpu-memory-utilization เหลือ 0.80
Request timeout 504 error ตอนโหลดหนัก เพิ่ม max concurrency และเพิ่ม instance
Request แรกช้า cold start แล้ว latency 30+ วินาที ยิง dummy request warm up ไว้ตอน startup
Model format ไม่รองรับ ขึ้น error ว่า model ไม่ compatible เช็กกับ list model ที่ vLLM รองรับ
TTFT (time to first token) สูง ใช้แบบโต้ตอบแล้วรู้สึกหน่วง ลด max input length และเปิด chunked prefill
Model ตอบผิด Quality แย่ลงเทียบกับ model ต้นฉบับ ลองเวอร์ชันที่ไม่ quantize ดูว่าเป็นที่ quantization หรือเปล่า
ไม่มี metrics มองไม่เห็นว่า production เป็นยังไง ต่อ /metrics เข้า Prometheus

สรุป

# 1. Install
pip install vllm

# 2. Offline inference (Python script)
python -c "
from vllm import LLM, SamplingParams
llm = LLM('Qwen/Qwen2.5-7B-Instruct')
out = llm.generate(['Hello, who are you?'], SamplingParams(max_tokens=100))
print(out[0].outputs[0].text)
"

# 3. OpenAI-compatible server
python -m vllm.entrypoints.openai.api_server \
    --model Qwen/Qwen2.5-7B-Instruct \
    --port 8000

# 4. Test the server
curl http://localhost:8000/v1/chat/completions \
    -H "Content-Type: application/json" \
    -d '{"model":"Qwen/Qwen2.5-7B-Instruct","messages":[{"role":"user","content":"Hi!"}]}'

# 5. Use with OpenAI SDK
python -c "
from openai import OpenAI
c = OpenAI(base_url='http://localhost:8000/v1', api_key='x')
r = c.chat.completions.create(model='Qwen/Qwen2.5-7B-Instruct', messages=[{'role':'user','content':'Hi!'}])
print(r.choices[0].message.content)
"

# 6. Production: Docker with GPU
docker run --runtime nvidia --gpus all -p 8000:8000 \
    vllm/vllm-openai:latest \
    --model Qwen/Qwen2.5-7B-Instruct-AWQ \
    --quantization awq \
    --enable-prefix-caching

vLLM กลายเป็นมาตรฐานของ open-source LLM serving ไปแล้ว เพราะแก้ปัญหาที่เจอจริงได้ครบ ทั้ง memory efficiency, throughput และใช้แทน OpenAI API ได้ทันที โดยไม่ต้องเขียนแอปใหม่ เริ่มจากเปิดโหมด OpenAI-compatible server ก่อน วัด throughput ด้วย benchmark tool แล้วค่อยจูนต่อจากตัวเลขที่ได้ ถ้าจะพาแอป LLM จาก prototype ขึ้น production การย้ายจาก model.generate() ตรงๆ มาใช้ vLLM คือการลงทุนที่คุ้มที่สุดอย่างหนึ่ง


มีคำถามหรืออยากคุยต่อ? ทักผมได้ทาง LinkedIn, X หรือ email

Discussion

Have thoughts on this post? Share them below — questions, corrections, or your own experience are all welcome.