在 vLLM 中集成 Transformers 建模后端
Hugging Face Transformers 库为庞大的模型架构生态系统提供了一个灵活、统一的接口。从研究到在自定义数据集上进行微调,Transformers 都是首选的工具包。
但当涉及到大规模部署这些模型时,推理速度和效率往往成为焦点。这时候 vLLM 就派上了用场,它是一个为高吞吐量推理而设计的库,可以从 Hugging Face Hub 中拉取模型并对其进行优化,以实现生产级的性能。
vLLM 代码库最近新增了一项功能,允许将 Transformers 用作模型实现的后端。因此,vLLM 将在现有 Transformers 架构之上优化吞吐量/延迟。在本文中,我们将探讨 vLLM 如何利用 Transformers 建模后端将灵活性与效率相结合,使你能够更快、更智能地部署最先进的模型。
更新
本节将包含自博客文章首次发布(2025 年 4 月 11 日)以来的所有更新。
支持视觉语言模型(2025 年 7 月 21 日)
vLLM 与 Transformers 建模后端现已支持视觉语言模型。当用户添加 model_impl="transformers" 时,系统将推断并加载适用于纯文本和多模态的正确类。
以下是如何使用 Transformers 建模后端来服务多模态模型。
vllm serve llava-hf/llava-onevision-qwen2-0.5b-ov-hf \
--model_impl transformers \
要使用该模型,可以像这样使用 openai API
from openai import OpenAI
openai_api_key = "EMPTY"
openai_api_base = "https://:8000/v1"
client = OpenAI(
api_key=openai_api_key,
base_url=openai_api_base,
)
chat_response = client.chat.completions.create(
model="llava-hf/llava-onevision-qwen2-0.5b-ov-hf",
messages=[{
"role": "user",
"content": [
{"type": "text", "text": "What's in this image?"},
{
"type": "image_url",
"image_url": {
"url": "http://images.cocodataset.org/val2017/000000039769.jpg",
},
},
],
}],
)
print("Chat response:", chat_response)
你也可以使用 LLM API 直接初始化 vLLM 引擎。下面是使用 LLM API 服务相同模型的示例。
from vllm import LLM, SamplingParams
from PIL import Image
import requests
from transformers import AutoProcessor
model_id = "llava-hf/llava-onevision-qwen2-0.5b-ov-hf"
hf_processor = AutoProcessor.from_pretrained(model_id) # required to dynamically update the chat template
messages = [
{
"role": "user",
"content": [
{"type": "image", "url": "dummy_image.jpg"},
{"type": "text", "text": "What is the content of this image?"},
],
},
]
prompt = hf_processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
image = Image.open(
requests.get(
"http://images.cocodataset.org/val2017/000000039769.jpg", stream=True
).raw
)
# initialize the vlm using the `model_impl="transformers"`
vlm = LLM(
model="llava-hf/llava-onevision-qwen2-0.5b-ov-hf",
model_impl="transformers",
)
outputs = vlm.generate(
{
"prompt": prompt,
"multi_modal_data": {"image": image},
},
sampling_params=SamplingParams(max_tokens=100)
)
for o in outputs:
generated_text = o.outputs[0].text
print(generated_text)
# OUTPUTS:
# In the tranquil setting of this image, two feline companions are enjoying a peaceful slumber on a
# cozy pink couch. The couch, adorned with a plush red fabric across the seating area, serves as their perfect resting place.
#
# On the left side of the couch, a gray tabby cat is curled up at rest, its body relaxed in a display
# of feline serenity. One paw playfully stretches out, perhaps in mid-jump or simply exploring its surroundings.
Transformers 与 vLLM:推理实战
让我们从一个简单的文本生成任务开始,使用 meta-llama/Llama-3.2-1B 模型来看看这两个库的表现如何。
使用 Transformers 进行推理
Transformers 库以其简洁性和多功能性而著称。使用其 pipeline API,推理变得轻而易举。
from transformers import pipeline
pipe = pipeline("text-generation", model="meta-llama/Llama-3.2-1B")
result = pipe("The future of AI is")
print(result[0]["generated_text"])
这种方法非常适合原型设计或小规模任务,但它并未针对大批量推理或低延迟部署进行优化。
使用 vLLM 进行推理
vLLM 采取了不同的路线,通过 PagedAttention(一种内存高效的注意力机制)和动态批处理等功能来优先考虑效率。下面是 vLLM 中相同的任务:
from vllm import LLM, SamplingParams
llm = LLM(model="meta-llama/Llama-3.2-1B")
params = SamplingParams(max_tokens=20)
outputs = llm.generate("The future of AI is", sampling_params=params)
print(f"Generated text: {outputs[0].outputs[0].text}")
vLLM 的推理速度明显更快,资源效率更高,尤其是在高负载情况下。例如,它可以用更低的 GPU 内存使用量处理每秒数千个请求。
vLLM 的部署超能力:与 OpenAI 兼容
除了原始性能,vLLM 还提供与 OpenAI 兼容的 API,使其可以作为外部服务的直接替代品。启动一个服务器:
vllm serve meta-llama/Llama-3.2-1B
然后用 curl 查询它:
curl https://:8000/v1/completions \
-H "Content-Type: application/json" \
-d '{"model": "meta-llama/Llama-3.2-1B", "prompt": "San Francisco is a", "max_tokens": 7, "temperature": 0}'
或者使用 Python 的 OpenAI 客户端:
from openai import OpenAI
client = OpenAI(api_key="EMPTY", base_url="https://:8000/v1")
completion = client.completions.create(
model="meta-llama/Llama-3.2-1B",
prompt="San Francisco is a",
max_tokens=7,
temperature=0
)
print("Completion result:", completion.choices[0].text)
这种兼容性大幅削减了成本并增强了控制力,让你能够利用 vLLM 的优化在本地扩展推理。
为什么我们需要 Transformers 建模后端?
Transformers 库为贡献和添加新模型进行了优化。而另一方面,向 vLLM 添加新模型则要复杂一些。
在理想世界中,我们希望新模型一添加到 Transformers 中就能在 vLLM 中使用。随着 Transformers 建模后端的集成,我们正向这个理想世界迈进。
这里是关于如何让你的 Transformers 模型与 vLLM 兼容以启用集成的官方文档。我们遵循了这个指南,并使 modeling_gpt2.py 与该集成兼容!你可以在这个 Transformers 拉取请求中查看更改。
对于一个已经在 Transformers 中(并与 vLLM 兼容)的模型,我们需要这样做:
llm = LLM(model="new-transformers-model", model_impl="transformers")
说明
添加 model_impl 参数并非强制要求。如果模型在 vLLM 中没有原生支持,vLLM 会自动切换到 Transformers 实现。
或者对于一个来自 Hugging Face Hub 的自定义模型:
llm = LLM(model="custom-hub-model", model_impl="transformers", trust_remote_code=True)
这个后端充当了一座桥梁,将 Transformers 的即插即用灵活性与 vLLM 的推理能力结合起来。你可以两全其美:用 Transformers 进行快速原型设计,用 vLLM 进行优化部署。
案例研究:Helium
vLLM 尚不支持 Kyutai 团队的 Helium。你可能想用 vLLM 对该模型进行优化推理,而这正是 Transformers 建模后端大显身手的地方。
让我们来看看实际操作:
vllm serve kyutai/helium-1-preview-2b --model-impl transformers
使用 OpenAI API 查询它:
from openai import OpenAI
openai_api_key = "EMPTY"
openai_api_base = "https://:8000/v1"
client = OpenAI(
api_key=openai_api_key,
base_url=openai_api_base,
)
completion = client.completions.create(model="kyutai/helium-1-preview-2b", prompt="What is AI?")
print("Completion result:", completion)
在这里,vLLM 高效地处理输入,利用 Transformers 建模后端无缝加载 kyutai/helium-1-preview-2b。与在 Transformers 中原生运行相比,vLLM 提供了更低的延迟和更好的资源利用率。
通过将 Transformers 的模型生态系统与 vLLM 的推理优化相结合,你将解锁一个既灵活又可扩展的工作流程。无论你是在为新模型制作原型、部署自定义创作,还是扩展多模态应用,这种组合都将加速你从研究到生产的路径。