1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

vLLM入門 オンプレで実現するLLM推論

Posted at

1. はじめに

vLLM (virtual LLM) は、大規模言語モデル(LLM)を「高速かつ効率的」にオンプレ/クラウドGPU上で推論・サービングするオープンソースライブラリです[1]。特徴としては以下のものが挙げられます。

  • メモリ効率の良い KV キャッシュ管理(PagedAttention)
  • 継続的バッチ処理(continuous batching)による高スループット
  • OpenAI 互換の API サーバーを内蔵
  • 多様なデコーディング戦略(並列サンプリング、ビームサーチ等)
  • マルチ GPU/分散推論対応 (内部アーキテクチャの詳細は Ubicloud[2]参照)

2. 動作環境・インストール

2.1 必要な環境

  • GPU + CUDA(推奨:CUDA 11.7 以上)
  • transformers

2.2 インストール

pip install vllm transformers

3. 基本の使い方

Llama 4 Scout 17B-16E Instructを用いて生成してみる[3][4]。

from transformers import AutoTokenizer, Llama4ForConditionalGeneration

model_id = "meta-llama/Llama-4-Scout-17B-16E-Instruct"

tokenizer = AutoTokenizer.from_pretrained(model_id)
model = Llama4ForConditionalGeneration.from_pretrained(
    model_id,
    attn_implementation="flex_attention",  # vLLM等で推奨
    device_map="auto",
    torch_dtype="bfloat16",
)

messages = [
    {"role": "user", "content": "LangChainについて解説して"}
]
inputs = tokenizer.apply_chat_template(
    messages,
    add_generation_prompt=True,
    return_tensors="pt",
    return_dict=True
).to(model.device)

outputs = model.generate(**inputs, max_new_tokens=256)
result = tokenizer.batch_decode(outputs[:, inputs["input_ids"].shape[-1]:])[0]
print(result)

# バッチ処理も可能
batch_messages = [
    [{"role": "user", "content": "MCPの今後は?"}],
    [{"role": "user", "content": "バイブコーディングとは?"}],
    [{"role": "user", "content": "AIエージェントとは?"}]
]
batch_inputs = tokenizer.apply_chat_template(
    batch_messages,
    add_generation_prompt=True,
    return_tensors="pt",
    return_dict=True
).to(model.device)

batch_outputs = model.generate(**batch_inputs, max_new_tokens=256)
for i, output in enumerate(batch_outputs):
    print(f"[{i}] {tokenizer.decode(output[batch_inputs['input_ids'].shape[-1]:], skip_special_tokens=True)}")

(余談) Llama 4 Scout 17B-16E Instructの特徴

  • 2025年4月5日公開されたMetaによるLlama 4シリーズの指示応答最適化モデル
  • 多言語対応(日本語含む)、大規模文脈長、指示応答・チャット用途に最適
  • 利用にはMeta社のLlama 4 Community Licenseへの同意が必要
  • transformers v4.51.0以上が必要、H100クラスGPU推奨

4. 主要コンポーネント

  1. EngineCore: 推論のスケジューリング・実行を担う中核
  2. Scheduler(連続バッチ): トークン単位でリクエストを混在バッチ化
  3. KVCacheManager(PagedAttention): KV テンソルを固定サイズブロックで管理
  4. ModelRunner: GPU 上での最適化実行
  5. AsyncLLM + IPC: GIL 回避の非同期通信により CPU/GPU 並列化

5. パフォーマンス最適化

  • FlashAttention-3 や CUDA Graph を有効化
  • dynamic tensor offloading の調整
  • バッチサイズ/max_num_batched_tokens の最適化
  • マルチ GPU 分散推論/Tensor Parallelism

6. 運用・デプロイ

  • OpenAI 互換 API(/v1/chat/completions)対応
  • SSE ストリーミング対応
  • Docker/Kubernetes コンテナ化
  • Prometheus メトリクス出力

7. メリット・デメリット

OpenAI API vLLM(自前運用)
コスト 従量課金(トークン単価) GPU インフラ運用で低コスト化可能
レイテンシ ネットワーク往復あり 直接 GPU 実行で低遅延
モデル選択 提供モデルのみ Hugging Face 全モデル対応
セキュリティ 外部送信あり 完全社内運用でデータ保護
手軽さ 即利用可能 初期設定・チューニング工数

参考文献

[1] Jimmy Wang, “LLMOps: vLLM for fast LLM inference,” Medium, Oct. 18, 2024.
[2] Ubicloud, “Life of an inference request (vLLM V1): How LLMs are served efficiently at scale,” Jun. 27, 2025.
[3] meta-llama/Llama-4-Scout-17B-16E-Instruct, Hugging Face, https://huggingface.co/meta-llama/Llama-4-Scout-17B-16E-Instruct
[4] meta-llama/Llama-4-Maverick-17B-128E-Instruct, Hugging Face, https://huggingface.co/meta-llama/Llama-4-Maverick-17B-128E-Instruct

1
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?