多模态输入¶
本页将教你如何将多模态输入传递给 vLLM 中的多模态模型。
注意
我们正在积极迭代多模态支持。请参阅 RFC 以了解即将进行的更改,如果您有任何反馈或功能请求,请在 GitHub 上提出 issue。
提示
在部署多模态模型时,请考虑设置 --allowed-media-domains 以限制 vLLM 可以访问的域,防止其访问可能容易受到服务器端请求伪造 (SSRF) 攻击的任意端点。您可以使用域列表为该参数赋值。例如:--allowed-media-domains upload.wikimedia.org github.com www.bogotobogo.com
另外,请考虑设置 VLLM_MEDIA_URL_ALLOW_REDIRECTS=0 以防止跟随 HTTP 重定向绕过域限制。
如果 vLLM 在容器化环境中运行,vLLM Pod 可能拥有对内部网络的无限制访问权限,因此此限制尤为重要。
离线推理¶
要输入多模态数据,请遵循 vllm.inputs.PromptType 中的该模式
prompt: prompt 应遵循 HuggingFace 上记录的格式。multi_modal_data: 这是一个字典,遵循 vllm.multimodal.inputs.MultiModalDataDict 中定义的模式。
缓存的稳定 UUID (multi_modal_uuids)¶
在使用多模态输入时,vLLM 通常会按内容对每个媒体项进行哈希处理,以便在请求之间进行缓存。您可以选择性地传递 multi_modal_uuids 来为每个项提供自己的稳定 ID,这样缓存就可以在请求之间重用工作,而无需重新哈希原始内容。
代码
from vllm import LLM
from PIL import Image
# Qwen2.5-VL example with two images
llm = LLM(model="Qwen/Qwen2.5-VL-3B-Instruct")
prompt = "USER: <image><image>\nDescribe the differences.\nASSISTANT:"
img_a = Image.open("/path/to/a.jpg")
img_b = Image.open("/path/to/b.jpg")
outputs = llm.generate({
"prompt": prompt,
"multi_modal_data": {"image": [img_a, img_b]},
# Provide stable IDs for caching.
# Requirements (matched by this example):
# - Include every modality present in multi_modal_data.
# - For lists, provide the same number of entries.
# - Use None to fall back to content hashing for that item.
"multi_modal_uuids": {"image": ["sku-1234-a", None]},
})
for o in outputs:
print(o.outputs[0].text)
使用 UUID,如果您期望缓存命中,甚至可以完全跳过发送媒体数据。请注意,如果跳过的媒体没有相应的 UUID,或者 UUID 缓存命中失败,则请求将失败。
代码
from vllm import LLM
from PIL import Image
# Qwen2.5-VL example with two images
llm = LLM(model="Qwen/Qwen2.5-VL-3B-Instruct")
prompt = "USER: <image><image>\nDescribe the differences.\nASSISTANT:"
img_b = Image.open("/path/to/b.jpg")
outputs = llm.generate({
"prompt": prompt,
"multi_modal_data": {"image": [None, img_b]},
# Since img_a is expected to be cached, we can skip sending the actual
# image entirely.
"multi_modal_uuids": {"image": ["sku-1234-a", None]},
})
for o in outputs:
print(o.outputs[0].text)
警告
如果禁用了多模态处理器缓存和前缀缓存,则用户提供的 multi_modal_uuids 将被忽略。
图像输入¶
您可以在多模态字典的 'image' 字段中传递单个图像,如下例所示
代码
from vllm import LLM
llm = LLM(model="llava-hf/llava-1.5-7b-hf")
# Refer to the HuggingFace repo for the correct format to use
prompt = "USER: <image>\nWhat is the content of this image?\nASSISTANT:"
# Load the image using PIL.Image
image = PIL.Image.open(...)
# Single prompt inference
outputs = llm.generate({
"prompt": prompt,
"multi_modal_data": {"image": image},
})
for o in outputs:
generated_text = o.outputs[0].text
print(generated_text)
# Batch inference
image_1 = PIL.Image.open(...)
image_2 = PIL.Image.open(...)
outputs = llm.generate(
[
{
"prompt": "USER: <image>\nWhat is the content of this image?\nASSISTANT:",
"multi_modal_data": {"image": image_1},
},
{
"prompt": "USER: <image>\nWhat's the color of this image?\nASSISTANT:",
"multi_modal_data": {"image": image_2},
}
]
)
for o in outputs:
generated_text = o.outputs[0].text
print(generated_text)
完整示例: examples/offline_inference/vision_language.py
要在同一个文本提示中替换多个图像,您可以传递图像列表
代码
from vllm import LLM
llm = LLM(
model="microsoft/Phi-3.5-vision-instruct",
trust_remote_code=True, # Required to load Phi-3.5-vision
max_model_len=4096, # Otherwise, it may not fit in smaller GPUs
limit_mm_per_prompt={"image": 2}, # The maximum number to accept
)
# Refer to the HuggingFace repo for the correct format to use
prompt = "<|user|>\n<|image_1|>\n<|image_2|>\nWhat is the content of each image?<|end|>\n<|assistant|>\n"
# Load the images using PIL.Image
image1 = PIL.Image.open(...)
image2 = PIL.Image.open(...)
outputs = llm.generate({
"prompt": prompt,
"multi_modal_data": {"image": [image1, image2]},
})
for o in outputs:
generated_text = o.outputs[0].text
print(generated_text)
完整示例: examples/offline_inference/vision_language_multi_image.py
如果使用 LLM.chat 方法,您可以直接在消息内容中使用各种格式的图像:图像 URL、PIL Image 对象或预计算的嵌入。
from vllm import LLM
from vllm.assets.image import ImageAsset
llm = LLM(model="llava-hf/llava-1.5-7b-hf")
image_url = "https://picsum.photos/id/32/512/512"
image_pil = ImageAsset('cherry_blossom').pil_image
image_embeds = torch.load(...)
conversation = [
{"role": "system", "content": "You are a helpful assistant"},
{"role": "user", "content": "Hello"},
{"role": "assistant", "content": "Hello! How can I assist you today?"},
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {"url": image_url},
},
{
"type": "image_pil",
"image_pil": image_pil,
},
{
"type": "image_embeds",
"image_embeds": image_embeds,
},
{
"type": "text",
"text": "What's in these images?",
},
],
},
]
# Perform inference and log output.
outputs = llm.chat(conversation)
for o in outputs:
generated_text = o.outputs[0].text
print(generated_text)
多图像输入可以扩展以执行视频字幕。我们使用 Qwen2-VL 来演示这一点,因为它支持视频。
代码
from vllm import LLM
# Specify the maximum number of frames per video to be 4. This can be changed.
llm = LLM("Qwen/Qwen2-VL-2B-Instruct", limit_mm_per_prompt={"image": 4})
# Create the request payload.
video_frames = ... # load your video making sure it only has the number of frames specified earlier.
message = {
"role": "user",
"content": [
{
"type": "text",
"text": "Describe this set of frames. Consider the frames to be a part of the same video.",
},
],
}
for i in range(len(video_frames)):
base64_image = encode_image(video_frames[i]) # base64 encoding.
new_image = {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{base64_image}"}}
message["content"].append(new_image)
# Perform inference and log output.
outputs = llm.chat([message])
for o in outputs:
generated_text = o.outputs[0].text
print(generated_text)
自定义 RGBA 背景颜色¶
加载 RGBA 图像(带透明度的图像)时,vLLM 会将其转换为 RGB 格式。默认情况下,透明像素会被白色背景替换。您可以通过 media_io_kwargs 中的 rgba_background_color 参数自定义此背景颜色。
代码
from vllm import LLM
# Default white background (no configuration needed)
llm = LLM(model="llava-hf/llava-1.5-7b-hf")
# Custom black background for dark theme
llm = LLM(
model="llava-hf/llava-1.5-7b-hf",
media_io_kwargs={"image": {"rgba_background_color": [0, 0, 0]}},
)
# Custom brand color background (e.g., blue)
llm = LLM(
model="llava-hf/llava-1.5-7b-hf",
media_io_kwargs={"image": {"rgba_background_color": [0, 0, 255]}},
)
注意
rgba_background_color接受 RGB 值,格式为列表[R, G, B]或元组(R, G, B),其中每个值在 0-255 之间。- 此设置仅影响 RGBA 图像的透明度;RGB 图像不受影响。
- 如果未指定,为兼容性起见,将使用默认的白色背景
(255, 255, 255)。
视频输入¶
您可以将 NumPy 数组列表直接传递给多模态字典的 'video' 字段,而不是使用多图像输入。
除了 NumPy 数组,您还可以传递 'torch.Tensor' 实例,如使用 Qwen2.5-VL 的此示例所示。
代码
from transformers import AutoProcessor
from vllm import LLM, SamplingParams
from qwen_vl_utils import process_vision_info
model_path = "Qwen/Qwen2.5-VL-3B-Instruct"
video_path = "https://content.pexels.com/videos/free-videos.mp4"
llm = LLM(
model=model_path,
gpu_memory_utilization=0.8,
enforce_eager=True,
limit_mm_per_prompt={"video": 1},
)
sampling_params = SamplingParams(max_tokens=1024)
video_messages = [
{
"role": "system",
"content": "You are a helpful assistant.",
},
{
"role": "user",
"content": [
{"type": "text", "text": "describe this video."},
{
"type": "video",
"video": video_path,
"total_pixels": 20480 * 28 * 28,
"min_pixels": 16 * 28 * 28,
},
]
},
]
messages = video_messages
processor = AutoProcessor.from_pretrained(model_path)
prompt = processor.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True,
)
image_inputs, video_inputs = process_vision_info(messages)
mm_data = {}
if video_inputs is not None:
mm_data["video"] = video_inputs
llm_inputs = {
"prompt": prompt,
"multi_modal_data": mm_data,
}
outputs = llm.generate([llm_inputs], sampling_params=sampling_params)
for o in outputs:
generated_text = o.outputs[0].text
print(generated_text)
注意
'process_vision_info' 仅适用于 Qwen2.5-VL 及类似模型。
完整示例: examples/offline_inference/vision_language.py
音频输入¶
您可以将元组 (array, sampling_rate) 传递给多模态字典的 'audio' 字段。
完整示例: examples/offline_inference/audio_language.py
嵌入输入¶
要将属于某个数据类型(例如图像、视频或音频)的预计算嵌入直接输入到语言模型中,请将形状为 (num_items, feature_size, LM 的 hidden_size) 的张量传递给多模态字典的相应字段。
您必须通过 enable_mm_embeds=True 来启用此功能。
警告
如果传递的嵌入形状不正确,vLLM 引擎可能会崩溃。仅对受信任的用户启用此标志!
图像嵌入¶
代码
from vllm import LLM
# Inference with image embeddings as input
llm = LLM(model="llava-hf/llava-1.5-7b-hf", enable_mm_embeds=True)
# Refer to the HuggingFace repo for the correct format to use
prompt = "USER: <image>\nWhat is the content of this image?\nASSISTANT:"
# Embeddings for single image
# torch.Tensor of shape (1, image_feature_size, hidden_size of LM)
image_embeds = torch.load(...)
outputs = llm.generate({
"prompt": prompt,
"multi_modal_data": {"image": image_embeds},
})
for o in outputs:
generated_text = o.outputs[0].text
print(generated_text)
对于 Qwen2-VL 和 MiniCPM-V,我们接受嵌入旁的额外参数。
代码
# Construct the prompt based on your model
prompt = ...
# Embeddings for multiple images
# torch.Tensor of shape (num_images, image_feature_size, hidden_size of LM)
image_embeds = torch.load(...)
# Qwen2-VL
llm = LLM(
"Qwen/Qwen2-VL-2B-Instruct",
limit_mm_per_prompt={"image": 4},
enable_mm_embeds=True,
)
mm_data = {
"image": {
"image_embeds": image_embeds,
# image_grid_thw is needed to calculate positional encoding.
"image_grid_thw": torch.load(...), # torch.Tensor of shape (1, 3),
}
}
# MiniCPM-V
llm = LLM(
"openbmb/MiniCPM-V-2_6",
trust_remote_code=True,
limit_mm_per_prompt={"image": 4},
enable_mm_embeds=True,
)
mm_data = {
"image": {
"image_embeds": image_embeds,
# image_sizes is needed to calculate details of the sliced image.
"image_sizes": [image.size for image in images], # list of image sizes
}
}
outputs = llm.generate({
"prompt": prompt,
"multi_modal_data": mm_data,
})
for o in outputs:
generated_text = o.outputs[0].text
print(generated_text)
对于 Qwen3-VL,image_embeds 应同时包含基本图像嵌入和深度堆栈特征。
音频嵌入输入¶
您可以像图像嵌入一样传递预计算的音频嵌入。
代码
from vllm import LLM
import torch
# Enable audio embeddings support
llm = LLM(model="fixie-ai/ultravox-v0_5-llama-3_2-1b", enable_mm_embeds=True)
# Refer to the HuggingFace repo for the correct format to use
prompt = "USER: <audio>\nWhat is in this audio?\nASSISTANT:"
# Load pre-computed audio embeddings
# torch.Tensor of shape (1, audio_feature_size, hidden_size of LM)
audio_embeds = torch.load(...)
outputs = llm.generate({
"prompt": prompt,
"multi_modal_data": {"audio": audio_embeds},
})
for o in outputs:
generated_text = o.outputs[0].text
print(generated_text)
在线服务¶
我们的 OpenAI 兼容服务器通过 Chat Completions API 接受多模态数据。媒体输入还支持可选的 UUID,用户可以提供这些 UUID 来唯一标识每个媒体,用于跨请求缓存媒体结果。
重要
使用 Chat Completions API 需要聊天模板。对于 HF 格式的模型,默认聊天模板定义在 chat_template.json 或 tokenizer_config.json 中。
如果没有默认聊天模板,我们将首先查找 内置的后备模板。如果没有后备模板,则会引发错误,您必须通过 --chat-template 参数手动提供聊天模板。
对于某些模型,我们在 示例 中提供了替代聊天模板。例如,VLM2Vec 使用 示例/template_vlm2vec_phi3v.jinja,这与 Phi-3-Vision 的默认模板不同。
图像输入¶
图像输入支持按照 OpenAI Vision API 进行。下面是一个使用 Phi-3.5-Vision 的简单示例。
首先,启动 OpenAI 兼容服务器
vllm serve microsoft/Phi-3.5-vision-instruct --runner generate \
--trust-remote-code --max-model-len 4096 --limit-mm-per-prompt '{"image":2}'
然后,您可以使用 OpenAI 客户端,如下所示
代码
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,
)
# Single-image input inference
image_url = "https://vllm-public-assets.s3.us-west-2.amazonaws.com/vision_model_images/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg"
chat_response = client.chat.completions.create(
model="microsoft/Phi-3.5-vision-instruct",
messages=[
{
"role": "user",
"content": [
# NOTE: The prompt formatting with the image token `<image>` is not needed
# since the prompt will be processed automatically by the API server.
{
"type": "text",
"text": "What’s in this image?",
},
{
"type": "image_url",
"image_url": {"url": image_url},
"uuid": image_url, # Optional
},
],
}
],
)
print("Chat completion output:", chat_response.choices[0].message.content)
# Multi-image input inference
image_url_duck = "https://vllm-public-assets.s3.us-west-2.amazonaws.com/multimodal_asset/duck.jpg"
image_url_lion = "https://vllm-public-assets.s3.us-west-2.amazonaws.com/multimodal_asset/lion.jpg"
chat_response = client.chat.completions.create(
model="microsoft/Phi-3.5-vision-instruct",
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": "What are the animals in these images?",
},
{
"type": "image_url",
"image_url": {"url": image_url_duck},
"uuid": image_url_duck, # Optional
},
{
"type": "image_url",
"image_url": {"url": image_url_lion},
"uuid": image_url_lion, # Optional
},
],
}
],
)
print("Chat completion output:", chat_response.choices[0].message.content)
完整示例: examples/online_serving/openai_chat_completion_client_for_multimodal.py
提示
vLLM 还支持从本地文件路径加载:启动 API 服务器/引擎时,您可以通过 --allowed-local-media-path 指定允许的本地媒体路径,并在 API 请求中将文件路径作为 url 传递。
提示
API 请求的文本内容中不需要放置图像占位符 - 它们已经由图像内容表示。事实上,您可以通过交替文本和图像内容,将图像占位符放在文本中间。
视频输入¶
您可以将视频文件通过 video_url 传递,而不是 image_url。下面是一个使用 LLaVA-OneVision 的简单示例。
首先,启动 OpenAI 兼容服务器
然后,您可以使用 OpenAI 客户端,如下所示
代码
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,
)
video_url = "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerFun.mp4"
## Use video url in the payload
chat_completion_from_url = client.chat.completions.create(
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": "What's in this video?",
},
{
"type": "video_url",
"video_url": {"url": video_url},
"uuid": video_url, # Optional
},
],
}
],
model=model,
max_completion_tokens=64,
)
result = chat_completion_from_url.choices[0].message.content
print("Chat completion output from image url:", result)
完整示例: examples/online_serving/openai_chat_completion_client_for_multimodal.py
自定义 RGBA 背景颜色¶
要为 RGBA 图像使用自定义背景颜色,请通过 --media-io-kwargs 传递 rgba_background_color 参数。
# Example: Black background for dark theme
vllm serve llava-hf/llava-1.5-7b-hf \
--media-io-kwargs '{"image": {"rgba_background_color": [0, 0, 0]}}'
# Example: Custom gray background
vllm serve llava-hf/llava-1.5-7b-hf \
--media-io-kwargs '{"image": {"rgba_background_color": [128, 128, 128]}}'
音频输入¶
音频输入支持按照 OpenAI Audio API 进行。下面是一个使用 Ultravox-v0.5-1B 的简单示例。
首先,启动 OpenAI 兼容服务器
然后,您可以使用 OpenAI 客户端,如下所示
代码
import base64
import requests
from openai import OpenAI
from vllm.assets.audio import AudioAsset
def encode_base64_content_from_url(content_url: str) -> str:
"""Encode a content retrieved from a remote url to base64 format."""
with requests.get(content_url) as response:
response.raise_for_status()
result = base64.b64encode(response.content).decode('utf-8')
return result
openai_api_key = "EMPTY"
openai_api_base = "https://:8000/v1"
client = OpenAI(
api_key=openai_api_key,
base_url=openai_api_base,
)
# Any format supported by librosa is supported
audio_url = AudioAsset("winning_call").url
audio_base64 = encode_base64_content_from_url(audio_url)
chat_completion_from_base64 = client.chat.completions.create(
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": "What's in this audio?",
},
{
"type": "input_audio",
"input_audio": {
"data": audio_base64,
"format": "wav",
},
"uuid": audio_url, # Optional
},
],
},
],
model=model,
max_completion_tokens=64,
)
result = chat_completion_from_base64.choices[0].message.content
print("Chat completion output from input audio:", result)
或者,您也可以传递 audio_url,这是音频输入 image_url 的对应项。
代码
chat_completion_from_url = client.chat.completions.create(
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": "What's in this audio?",
},
{
"type": "audio_url",
"audio_url": {"url": audio_url},
"uuid": audio_url, # Optional
},
],
}
],
model=model,
max_completion_tokens=64,
)
result = chat_completion_from_url.choices[0].message.content
print("Chat completion output from audio url:", result)
完整示例: examples/online_serving/openai_chat_completion_client_for_multimodal.py
嵌入输入¶
要将属于某个数据类型(例如图像、视频或音频)的预计算嵌入直接输入到语言模型中,请将形状为 (num_items, feature_size, LM 的 hidden_size) 的张量传递给多模态字典的相应字段。
您必须通过 vllm serve 中的 --enable-mm-embeds 标志来启用此功能。
警告
如果传递的嵌入形状不正确,vLLM 引擎可能会崩溃。仅对受信任的用户启用此标志!
图像嵌入输入¶
对于图像嵌入,您可以将 base64 编码的张量传递给 image_embeds 字段。以下示例演示了如何将图像嵌入传递给 OpenAI 服务器。
代码
from vllm.utils.serial_utils import tensor2base64
image_embedding = torch.load(...)
grid_thw = torch.load(...) # Required by Qwen/Qwen2-VL-2B-Instruct
base64_image_embedding = tensor2base64(image_embedding)
client = OpenAI(
# defaults to os.environ.get("OPENAI_API_KEY")
api_key=openai_api_key,
base_url=openai_api_base,
)
# Basic usage - this is equivalent to the LLaVA example for offline inference
model = "llava-hf/llava-1.5-7b-hf"
embeds = {
"type": "image_embeds",
"image_embeds": f"{base64_image_embedding}",
"uuid": image_url, # Optional
}
# Pass additional parameters (available to Qwen2-VL and MiniCPM-V)
model = "Qwen/Qwen2-VL-2B-Instruct"
embeds = {
"type": "image_embeds",
"image_embeds": {
"image_embeds": f"{base64_image_embedding}", # Required
"image_grid_thw": f"{base64_image_grid_thw}", # Required by Qwen/Qwen2-VL-2B-Instruct
},
"uuid": image_url, # Optional
}
model = "openbmb/MiniCPM-V-2_6"
embeds = {
"type": "image_embeds",
"image_embeds": {
"image_embeds": f"{base64_image_embedding}", # Required
"image_sizes": f"{base64_image_sizes}", # Required by openbmb/MiniCPM-V-2_6
},
"uuid": image_url, # Optional
}
chat_completion = client.chat.completions.create(
messages=[
{
"role": "system",
"content": "You are a helpful assistant.",
},
{
"role": "user",
"content": [
{
"type": "text",
"text": "What's in this image?",
},
embeds,
],
},
],
model=model,
)
对于在线服务,您也可以在期望通过提供的 UUID 缓存命中时跳过发送媒体。您可以这样做:
```python
# Image/video/audio URL:
{
"type": "image_url",
"image_url": None,
"uuid": image_uuid,
},
# image_embeds
{
"type": "image_embeds",
"image_embeds": None,
"uuid": image_uuid,
},
# input_audio:
{
"type": "input_audio",
"input_audio": None,
"uuid": audio_uuid,
},
# PIL Image:
{
"type": "image_pil",
"image_pil": None,
"uuid": image_uuid,
},
```
注意
现在,多个消息可以包含 {"type": "image_embeds"},使您可以在单个请求中传递多个图像嵌入(类似于普通图像)。嵌入数量受 --limit-mm-per-prompt 的限制。
重要提示:嵌入的形状格式因嵌入数量而异
- 单个嵌入:形状为
(1, feature_size, hidden_size)的 3D 张量 - 多个嵌入:2D 张量列表,每个形状为
(feature_size, hidden_size)
如果与需要额外参数的模型一起使用,您还必须为每个参数提供一个张量,例如 image_grid_thw、image_sizes 等。