DEV Community

Cover image for vLLM là gì? Tăng tốc suy luận LLM cho API nhanh và mở rộng
Sebastian Petrus
Sebastian Petrus

Posted on • Originally published at apidog.com

vLLM là gì? Tăng tốc suy luận LLM cho API nhanh và mở rộng

Bạn đang xây dựng ứng dụng LLM và gặp vấn đề với suy luận chậm, giới hạn VRAM hoặc chi phí GPU tăng nhanh? vLLM là một inference engine mã nguồn mở giúp phục vụ LLM với thông lượng cao, tối ưu bộ nhớ và API tương thích OpenAI. Bài viết này hướng dẫn cách cài đặt, chạy batch inference, expose API realtime và xử lý các lỗi thường gặp khi triển khai vLLM.

Dùng thử Apidog ngay hôm nay

vLLM là gì? Vì sao quan trọng với API LLM?

vLLM là một inference engine mã nguồn mở được thiết kế để phục vụ các mô hình ngôn ngữ lớn với thông lượng cao và sử dụng bộ nhớ hiệu quả.

Khi triển khai LLM vào sản phẩm, bạn thường gặp hai vấn đề chính:

  • Suy luận chậm: đặc biệt khi có nhiều request đồng thời hoặc cần xử lý batch lớn.
  • Tốn VRAM: cơ chế attention truyền thống có thể lãng phí bộ nhớ GPU, làm giảm kích thước model hoặc số lượng request có thể phục vụ.

vLLM giải quyết các vấn đề này bằng hai kỹ thuật cốt lõi:

  • PagedAttention: quản lý KV cache theo cơ chế phân trang, giảm lãng phí bộ nhớ GPU.
  • Continuous batching: gom và xử lý request động khi tài nguyên GPU sẵn sàng, thay vì chờ đủ batch tĩnh.

Nếu bạn đang xây dựng API LLM tự host, vLLM có thể đóng vai trò backend inference để phục vụ các endpoint tương thích OpenAI.

Khi nào nên dùng vLLM?

vLLM phù hợp nếu bạn cần:

  • Phục vụ nhiều request LLM đồng thời.
  • Tối ưu chi phí GPU.
  • Tự host model thay vì gọi API bên ngoài.
  • Chạy batch inference để tạo dữ liệu, đánh giá model hoặc xử lý hàng loạt.
  • Expose API tương thích OpenAI để dễ tích hợp với client hiện có.
  • Thử nghiệm nhiều model từ Hugging Face hoặc ModelScope.

Các model phổ biến được hỗ trợ gồm Llama, Mistral, Mixtral, Qwen, OPT, Falcon, GPT-J, GPT-NeoX và nhiều model khác.

Xem danh sách đầy đủ tại: tài liệu model được hỗ trợ của vLLM.

Mẹo: Nếu bạn đang thiết kế, kiểm thử hoặc viết tài liệu cho API LLM, có thể dùng Apidog để quản lý endpoint, test request/response và cộng tác QA cho API dùng vLLM, OpenAI hoặc backend tùy chỉnh.

Các LLM được hỗ trợ

vLLM hỗ trợ nhiều kiến trúc transformer, bao gồm:

  • Llama: Llama, Llama 2, Llama 3
  • Mistral và Mixtral
  • Qwen và Qwen2
  • GPT-2, GPT-J, GPT-NeoX
  • OPT
  • Bloom
  • Falcon
  • MPT
  • Một số model đa phương thức

Danh sách này thay đổi theo thời gian. Trước khi triển khai, hãy kiểm tra Danh sách Mô hình được hỗ trợ chính thức của vLLM.

Nếu model của bạn chưa có trong danh sách nhưng kiến trúc tương tự model được hỗ trợ, bạn có thể thử nghiệm. Với kiến trúc tùy chỉnh, có thể cần trust_remote_code=True hoặc bổ sung mã nguồn tương thích.

Hai khái niệm quan trọng: PagedAttention và Continuous Batching

PagedAttention

Vấn đề: KV cache trong attention truyền thống thường cần vùng nhớ liền kề. Điều này dễ gây phân mảnh và lãng phí VRAM.

Cách vLLM xử lý: PagedAttention chia KV cache thành các “page”, tương tự bộ nhớ ảo trong hệ điều hành. Nhờ đó, vLLM có thể quản lý bộ nhớ linh hoạt hơn và giảm lãng phí khi phục vụ nhiều request.

Continuous Batching

Vấn đề: Batch tĩnh thường chờ đủ số request rồi mới chạy. Điều này làm GPU có thời gian rảnh và tăng latency.

Cách vLLM xử lý: Continuous batching thêm request mới vào luồng xử lý khi GPU có tài nguyên, giúp tăng throughput và giảm thời gian chờ.

Điều kiện tiên quyết

Trước khi cài đặt vLLM, hãy chuẩn bị:

  • Hệ điều hành: Linux là lựa chọn tốt nhất. WSL2 và macOS có thể dùng trong một số trường hợp, nhưng Linux được hỗ trợ tốt hơn.
  • Python: 3.9, 3.10, 3.11 hoặc 3.12.
  • GPU NVIDIA + CUDA: khuyến nghị cho hiệu năng tốt nhất.
  • PyTorch: vLLM thường tự cài phiên bản phù hợp, nhưng bạn có thể cài trước nếu cần cấu hình CUDA riêng.
  • Dung lượng đĩa: đủ để tải model từ Hugging Face hoặc lưu model cục bộ.

Cài đặt vLLM

Cách 1: Cài bằng pip

python -m venv vllm-env
source vllm-env/bin/activate

# Windows:
# vllm-env\Scripts\activate

pip install vllm
Enter fullscreen mode Exit fullscreen mode

Kiểm tra phiên bản:

python -c "import vllm; print(vllm.__version__)"
vllm --help
Enter fullscreen mode Exit fullscreen mode

Cách 2: Cài bằng Conda

conda create -n vllm-env python=3.11 -y
conda activate vllm-env
pip install vllm
Enter fullscreen mode Exit fullscreen mode

Nếu bạn cần bản PyTorch tương thích CUDA cụ thể, hãy cài PyTorch trước rồi mới cài vLLM.

Cách 3: Cài bằng uv

uv venv vllm-env --python 3.12 --seed
source vllm-env/bin/activate
uv pip install vllm
Enter fullscreen mode Exit fullscreen mode

Chạy batch inference với vLLM

Batch inference phù hợp cho các tác vụ như:

  • Đánh giá model.
  • Sinh dữ liệu.
  • Xử lý nhiều prompt ngoại tuyến.
  • Benchmark chất lượng hoặc latency.

Ví dụ:

from vllm import LLM, SamplingParams

# 1. Danh sách prompt
prompts = [
    "The capital of France is",
    "Explain the theory of relativity in simple terms:",
    "Write a short poem about a rainy day:",
    "Translate 'Hello, world!' to German:",
]

# 2. Cấu hình sampling
sampling_params = SamplingParams(
    temperature=0.7,
    top_p=0.95,
    max_tokens=150,
    stop=["\n", " Human:", " Assistant:"]
)

# 3. Khởi tạo engine vLLM
llm = LLM(model="mistralai/Mistral-7B-Instruct-v0.1")

# 4. Sinh output
outputs = llm.generate(prompts, sampling_params)

# 5. In kết quả
for output in outputs:
    print("-" * 20)
    print(f"Prompt: {output.prompt!r}")
    print(f"Generated Text: {output.outputs[0].text!r}")
    print("-" * 20)
Enter fullscreen mode Exit fullscreen mode

Một số lưu ý khi chạy batch:

  • Mặc định, vLLM tải model từ Hugging Face Hub.
  • Nếu dùng ModelScope, đặt biến môi trường:
export VLLM_USE_MODELSCOPE=1
Enter fullscreen mode Exit fullscreen mode
  • Nếu muốn dùng cấu hình generation mặc định của vLLM thay vì config từ model:
llm = LLM(
    model="mistralai/Mistral-7B-Instruct-v0.1",
    generation_config="vllm"
)
Enter fullscreen mode Exit fullscreen mode
  • Với model lượng tử hóa như AWQ hoặc GPTQ, hãy kiểm tra tài liệu vLLM và model card trên Hugging Face.

Chạy vLLM như API server tương thích OpenAI

vLLM có thể expose API tương thích OpenAI, giúp bạn tái sử dụng client hoặc SDK hiện có.

Khởi động server

source vllm-env/bin/activate

vllm serve mistralai/Mistral-7B-Instruct-v0.1
Enter fullscreen mode Exit fullscreen mode

Ví dụ với model khác:

vllm serve Qwen/Qwen2-1.5B-Instruct
Enter fullscreen mode Exit fullscreen mode

Mặc định server chạy tại:

http://localhost:8000
Enter fullscreen mode Exit fullscreen mode

Một số option thường dùng:

vllm serve mistralai/Mistral-7B-Instruct-v0.1 \
  --host 0.0.0.0 \
  --port 8000 \
  --api-key your-api-key
Enter fullscreen mode Exit fullscreen mode

Các tham số hữu ích:

  • --host 0.0.0.0: cho phép truy cập từ máy khác.
  • --port 8000: chỉ định cổng.
  • --tensor-parallel-size <N>: chia model trên N GPU.
  • --api-key <key>: yêu cầu API key cho request.
  • --generation-config vllm: dùng generation config của vLLM.
  • --chat-template <path>: dùng chat template tùy chỉnh.

Gọi endpoint /v1/completions

cURL

curl http://localhost:8000/v1/completions \
    -H "Content-Type: application/json" \
    -d '{
        "model": "mistralai/Mistral-7B-Instruct-v0.1",
        "prompt": "San Francisco is a city in",
        "max_tokens": 50,
        "temperature": 0.7
    }'
Enter fullscreen mode Exit fullscreen mode

Nếu server bật API key:

curl http://localhost:8000/v1/completions \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer your-api-key" \
    -d '{
        "model": "mistralai/Mistral-7B-Instruct-v0.1",
        "prompt": "Explain the benefits of using vLLM:",
        "max_tokens": 150,
        "temperature": 0.5
    }'
Enter fullscreen mode Exit fullscreen mode

Python với OpenAI client

from openai import OpenAI

client = OpenAI(
    api_key="EMPTY",
    base_url="http://localhost:8000/v1"
)

completion = client.completions.create(
    model="mistralai/Mistral-7B-Instruct-v0.1",
    prompt="Explain the benefits of using vLLM:",
    max_tokens=150,
    temperature=0.5
)

print(completion.choices[0].text)
Enter fullscreen mode Exit fullscreen mode

Nếu bạn cấu hình API key:

client = OpenAI(
    api_key="your-api-key",
    base_url="http://localhost:8000/v1"
)
Enter fullscreen mode Exit fullscreen mode

Gọi endpoint /v1/chat/completions

cURL

curl http://localhost:8000/v1/chat/completions \
    -H "Content-Type: application/json" \
    -d '{
        "model": "mistralai/Mistral-7B-Instruct-v0.1",
        "messages": [
            {"role": "system", "content": "You are a helpful assistant."},
            {"role": "user", "content": "What is the main advantage of PagedAttention in vLLM?"}
        ],
        "max_tokens": 100,
        "temperature": 0.7
    }'
Enter fullscreen mode Exit fullscreen mode

Python

from openai import OpenAI

client = OpenAI(
    api_key="EMPTY",
    base_url="http://localhost:8000/v1"
)

chat_response = client.chat.completions.create(
    model="mistralai/Mistral-7B-Instruct-v0.1",
    messages=[
        {"role": "system", "content": "You are a helpful programming assistant."},
        {"role": "user", "content": "Write a simple Python function to calculate factorial."}
    ],
    max_tokens=200,
    temperature=0.5
)

print(chat_response.choices[0].message.content)
Enter fullscreen mode Exit fullscreen mode

Với các endpoint kiểu OpenAI này, bạn có thể import vào công cụ API như Apidog để thiết kế request, kiểm thử response, viết tài liệu và tự động hóa QA cho backend LLM.

Backend attention trong vLLM

vLLM hỗ trợ nhiều backend attention để tối ưu tốc độ và bộ nhớ:

  • FlashAttention 1 & 2: thường phù hợp với GPU NVIDIA hiện đại.
  • xFormers: tương thích rộng hơn, hữu ích với một số phần cứng hoặc cấu hình cũ hơn.
  • FlashInfer: backend nâng cao, có thể cần cài đặt thủ công tùy môi trường.

Mặc định, vLLM tự chọn backend phù hợp với phần cứng và model.

Nếu muốn chỉ định thủ công:

export VLLM_ATTENTION_BACKEND=FLASH_ATTN
Enter fullscreen mode Exit fullscreen mode

Hoặc:

export VLLM_ATTENTION_BACKEND=XFORMERS
Enter fullscreen mode Exit fullscreen mode

Hoặc:

export VLLM_ATTENTION_BACKEND=FLASHINFER
Enter fullscreen mode Exit fullscreen mode

Sau đó chạy lại server:

vllm serve mistralai/Mistral-7B-Instruct-v0.1
Enter fullscreen mode Exit fullscreen mode

Khắc phục lỗi thường gặp

1. CUDA Out of Memory

Nếu gặp lỗi hết VRAM:

CUDA out of memory
Enter fullscreen mode Exit fullscreen mode

Thử các cách sau:

  • Dùng model nhỏ hơn.
  • Giảm max_tokens.
  • Giảm số request đồng thời.
  • Dùng model lượng tử hóa như AWQ hoặc GPTQ nếu phù hợp.
  • Chạy tensor parallel trên nhiều GPU:
vllm serve mistralai/Mistral-7B-Instruct-v0.1 \
  --tensor-parallel-size 2
Enter fullscreen mode Exit fullscreen mode
  • Kiểm tra process đang dùng GPU:
nvidia-smi
Enter fullscreen mode Exit fullscreen mode

2. Lỗi cài đặt hoặc không tương thích CUDA

Kiểm tra:

  • Driver NVIDIA.
  • Phiên bản CUDA.
  • Phiên bản PyTorch.
  • Python version.

Bạn có thể tham khảo bảng tương thích PyTorch.

Nếu muốn giảm rủi ro cấu hình môi trường, có thể dùng ảnh Docker vLLM chính thức.

3. Lỗi tải model

Các nguyên nhân thường gặp:

  • Sai tên model.
  • Model cần quyền truy cập trên Hugging Face.
  • Model yêu cầu trust_remote_code=True.
  • Không đủ dung lượng đĩa.
  • Mất kết nối mạng khi tải model.

Ví dụ dùng đường dẫn model cục bộ:

from vllm import LLM

llm = LLM(model="/path/to/local/model")
Enter fullscreen mode Exit fullscreen mode

4. Suy luận chậm

Nếu latency cao hoặc throughput thấp:

  • Kiểm tra GPU utilization:
nvidia-smi
Enter fullscreen mode Exit fullscreen mode
  • Cập nhật vLLM, PyTorch và driver NVIDIA.
  • Thử backend attention khác.
  • Giảm max_tokens.
  • Kiểm tra prompt có quá dài không.
  • Đảm bảo model phù hợp với VRAM hiện có.

5. Output sai định dạng hoặc vô nghĩa

Thử các bước sau:

  • Kiểm tra chat template của model.
  • Dùng đúng định dạng prompt được khuyến nghị trong model card.
  • Điều chỉnh temperature, top_p.
  • Giảm hoặc tăng max_tokens tùy use case.
  • Thử model khác để xác định lỗi do model hay do cấu hình serving.

Ví dụ giảm độ ngẫu nhiên:

sampling_params = SamplingParams(
    temperature=0.2,
    top_p=0.9,
    max_tokens=200
)
Enter fullscreen mode Exit fullscreen mode

Quy trình triển khai API LLM với vLLM

Một workflow thực tế có thể như sau:

  1. Chọn model phù hợp với use case và VRAM.
  2. Chạy batch inference để kiểm tra chất lượng output.
  3. Khởi động vLLM API server với endpoint tương thích OpenAI.
  4. Test bằng cURL hoặc OpenAI client.
  5. Import endpoint vào công cụ API như Apidog để thiết kế, test và viết tài liệu.
  6. Bật API key nếu expose server ra môi trường dùng chung.
  7. Theo dõi GPU, latency và throughput trong quá trình vận hành.
  8. Tối ưu model, sampling params và backend attention dựa trên kết quả thực tế.

Các bước tiếp theo

vLLM giúp bạn triển khai API LLM tự host với hiệu năng tốt hơn nhờ PagedAttention, continuous batching và API tương thích OpenAI.

Để đi xa hơn, hãy tìm hiểu thêm các tính năng nâng cao như:

  • Quantization.
  • Multi-LoRA.
  • Distributed serving.
  • Speculative decoding.
  • Cấu hình production deployment.

Tài liệu chính thức: https://docs.vllm.ai/en/stable/

Khi API đã sẵn sàng, bạn có thể kết hợp vLLM với Apidog để thiết kế, kiểm thử, mô phỏng và ghi tài liệu endpoint LLM trong cùng một workflow.

Top comments (0)