1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

UbuntuでvLLMを使いこなす完全ガイド【実例多数】

1
Posted at

対象: LLMをローカルGPUで高速推論したいエンジニア
環境: Ubuntu + NVIDIA GPU
この記事でわかること:

  • vLLMの概要と2つの使い方
  • Ubuntu上でのセットアップ手順
  • 実際のPython・APIコード例
  • 性能チューニングや運用Tips

🧠 vLLMとは?

vLLM は、OpenAI API互換で動作する 超高速 LLM 推論エンジン です。
特徴は以下の通り👇

  • PagedAttention による効率的なKVキャッシュ管理
  • Continuous Batching によるスループット向上
  • OpenAI互換APIサーバーを内蔵
  • Hugging Faceモデル互換
  • LoRA / 量子化 / スペキュレイティブデコーディングにも対応

🛠️ 環境準備(Ubuntu)

1. 基本要件

nvidia-smi
python3 --version
  • GPU: NVIDIA(CUDA対応)
  • Python: 3.10 以上推奨

2. 仮想環境作成

sudo apt update && sudo apt install -y python3-venv git
python3 -m venv ~/venv/vllm
source ~/venv/vllm/bin/activate
pip install --upgrade pip

⚙️ vLLMインストール

方法①:pip で簡単導入

pip install "vllm>=0.5" "torch>=2.2" "hf-transfer"

CPUだけで動かす場合(試験用):

pip install "vllm[cpu]>=0.5"

方法②:Dockerで汚さず起動

docker run --gpus all --rm -it -p 8000:8000 \
  -v $HOME/.cache/huggingface:/root/.cache/huggingface \
  ghcr.io/vllm-project/vllm-openai:latest \
  python -m vllm.entrypoints.openai.api_server \
  --model meta-llama/Meta-Llama-3-8B-Instruct

🏃 最小構成で動かしてみる

1. OpenAI互換APIサーバ

export HUGGING_FACE_HUB_TOKEN=hf_xxx  # gatedモデル利用時
vllm serve meta-llama/Meta-Llama-3-8B-Instruct \
  --port 8000 --max-model-len 8192 --gpu-memory-utilization 0.9

2. Pythonクライアント

from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="dummy")

res = client.chat.completions.create(
    model="meta-llama/Meta-Llama-3-8B-Instruct",
    messages=[{"role": "user", "content": "日本語で自己紹介して"}]
)
print(res.choices[0].message.content)

3. curlでも試せる

curl http://localhost:8000/v1/chat/completions \
  -H "Content-Type: application/json" -H "Authorization: Bearer dummy" \
  -d '{
    "model":"meta-llama/Meta-Llama-3-8B-Instruct",
    "messages":[{"role":"user","content":"三行で要約して"}],
    "stream":true
  }'

🧩 Python APIでバッチ推論

from vllm import LLM, SamplingParams

llm = LLM(model="mistralai/Mistral-7B-Instruct-v0.3")
params = SamplingParams(temperature=0.7, max_tokens=128)

prompts = [
    "List three benefits of containerization.",
    "日本語でゼロトラストの概念を説明して。"
]

outs = llm.generate(prompts, params)
for o in outs:
    print(o.outputs[0].text.strip())

💾 VRAMの目安

モデル サイズ VRAM目安 (FP16)
7B系 (Llama/Mistral) 8B 約16GB
13B系 13B 約28GB
量子化モデル (AWQ/GPTQ) 4bit 約半分以下

例:

vllm serve TheBloke/Mistral-7B-Instruct-v0.2-AWQ --port 8000

⚡ スループット最適化Tips

設定 推奨値 説明
--gpu-memory-utilization 0.85〜0.95 VRAMギリギリまで使う
--max-model-len 4096〜8192 長文対応
--tensor-parallel-size GPU枚数 分散実行
--trust-remote-code 一部モデルで必須 HFコード実行許可

LoRA併用例

vllm serve mistralai/Mistral-7B-Instruct-v0.3 \
  --lora-modules ja:lora-org/ja-helpdesk-lora \
  --lora-modules en:lora-org/en-helpdesk-lora

🧪 並列テストコード

import concurrent.futures, time
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="dummy")

def ask(i):
    r = client.chat.completions.create(
        model="mistralai/Mistral-7B-Instruct-v0.3",
        messages=[{"role":"user","content":f"ID:{i} NginxのOOM対策を一言で"}],
        max_tokens=64)
    return r.choices[0].message.content

t0 = time.time()
with concurrent.futures.ThreadPoolExecutor(max_workers=32) as ex:
    outs = list(ex.map(ask, range(100)))
print(f"{len(outs)} reqs in {time.time()-t0:.1f}s")

🧰 運用Tips

Systemd常駐化

/etc/systemd/system/vllm.service

[Service]
ExecStart=/home/ubuntu/venv/vllm/bin/vllm serve meta-llama/Meta-Llama-3-8B-Instruct --port 8000
Restart=always
Environment=HUGGING_FACE_HUB_TOKEN=hf_xxx
sudo systemctl daemon-reload
sudo systemctl enable --now vllm

よくあるトラブル

症状 原因 対処
CUDA out of memory VRAM不足 量子化モデルを利用
モデルDL遅い ネット転送 pip install hf-transfer
Dockerでエラー /dev/shm不足 --shm-size 2g

🔒 セキュリティ設計のポイント

  • サーバは社内VPC内で運用
  • APIキー / mTLSでアクセス制限
  • プロンプトログはPIIマスク必須
  • モデルライセンスの商用可否を確認

🧠 まとめ

項目 要点
目的 LLMをローカルGPUでOpenAI互換APIとして運用
ツール vLLM(超高速推論エンジン)
利点 高スループット・低レイテンシ・OpenAI互換
応用 RAG / LoRA / 社内ChatGPT構築 / バッチ推論

💬 次のステップ

  • --speculative-model で軽量モデル併用
  • LangChainやLlamaIndexとの統合
  • Grafanaでメトリクス監視
  • 社内OpenAI互換APIとして共通化

🏁 結論

「vLLM serve」でOpenAI互換APIを立てれば、自前GPUがChatGPTになる。
Ubuntuでも1時間あれば構築可能。
あとは業務データをつなぐだけで“社内生成AI”が動き出します。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?