部署视觉 LLM#

   

视觉 LLM 可以像解释文本一样解释图像,从而能够处理诸如回答图表问题、分析照片或将视觉信息与指令结合等任务。它将 LLM 的能力从语言扩展到支持多模态推理和更丰富的应用。

本教程将使用 Ray Serve LLM 部署一个视觉 LLM。


配置 Ray Serve LLM#

请确保在配置文件中设置您的 Hugging Face Token,以便访问受限模型。

Ray Serve LLM 提供了多种 Python API 来定义您的应用程序。使用 build_openai_app 从您的 LLMConfig 对象构建完整的应用程序。

# serve_qwen_VL.py
from ray.serve.llm import LLMConfig, build_openai_app
import os

llm_config = LLMConfig(
    model_loading_config=dict(
        model_id="my-qwen-VL",
        model_source="qwen/Qwen2.5-VL-7B-Instruct",
    ),
    accelerator_type="L40S", # Or "A100-40G"
    deployment_config=dict(
        autoscaling_config=dict(
            min_replicas=1,
            max_replicas=2,
        )
    ),
    ### Uncomment if your model is gated and needs your Hugging Face token to access it.
    # runtime_env=dict(env_vars={"HF_TOKEN": os.environ.get("HF_TOKEN")}),
    engine_kwargs=dict(max_model_len=8192),
)

app = build_openai_app({"llm_configs": [llm_config]})

注意:在迁移到生产环境之前,请迁移到 Serve 配置文件,以便您的部署版本控制、可重现,并且更容易维护 CI/CD 管道。请参阅服务 LLM - 快速入门示例:生产指南以获取示例。


本地部署#

先决条件

  • GPU 计算访问权限。

  • (可选)**Hugging Face Token**,如果您使用受限模型。将其存储在 export HF_TOKEN=<YOUR-TOKEN-HERE>

注意:根据情况,您通常可以在模型的 Hugging Face 页面上请求访问权限。例如,Meta 的 Llama 模型批准可能需要几小时到几周的时间。

依赖项

pip install "ray[serve,llm]"

启动#

请按照 配置 Ray Serve LLM 中的说明,在 Python 模块 serve_qwen_VL.py 中定义您的应用。

在终端中,运行

serve run serve_qwen_VL:app --non-blocking

部署通常需要几分钟时间,因为集群会被配置、vLLM 服务器会启动,并且模型会被下载。


发送带图像的请求#

您的端点在本地的 https://:8000 上可用,您可以使用占位符认证 token 来访问 OpenAI 客户端,例如 "FAKE_KEY"

带图像 URL 的示例 curl

curl -X POST http://localhost:8000/v1/chat/completions \
  -H "Authorization: Bearer FAKE_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "model": "my-qwen-VL", "messages": [ { "role": "user", "content": [ {"type": "text", "text": "What do you see in this image?"}, {"type": "image_url", "image_url": { "url": "http://images.cocodataset.org/val2017/000000039769.jpg" }} ] } ] }'

带图像 URL 的示例 Python

#client_url_image.py
from urllib.parse import urljoin
from openai import OpenAI

API_KEY = "FAKE_KEY"
BASE_URL = "https://:8000"

client = OpenAI(base_url=urljoin(BASE_URL, "v1"), api_key=API_KEY)

response = client.chat.completions.create(
    model="my-qwen-VL",
    messages=[
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "What is in this image?"},
                {"type": "image_url", "image_url": {"url": "http://images.cocodataset.org/val2017/000000039769.jpg"}}
            ]
        }
    ],
    temperature=0.5,
    stream=True
)

for chunk in response:
    content = chunk.choices[0].delta.content
    if content:
        print(content, end="", flush=True)

带本地图像的示例 Python

#client_local_image.py
from urllib.parse import urljoin
import base64
from openai import OpenAI

API_KEY = "FAKE_KEY"
BASE_URL = "https://:8000"

client = OpenAI(base_url=urljoin(BASE_URL, "v1"), api_key=API_KEY)

### From an image locally saved as `example.jpg`
# Load and encode image as base64
with open("example.jpg", "rb") as f:
    img_base64 = base64.b64encode(f.read()).decode()

response = client.chat.completions.create(
    model="my-qwen-VL",
    messages=[
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "What is in this image?"},
                {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{img_base64}"}}
            ]
        }
    ],
    temperature=0.5,
    stream=True
)

for chunk in response:
    content = chunk.choices[0].delta.content
    if content:
        print(content, end="", flush=True)

关停#

关停您的 LLM 服务

serve shutdown -y

使用 Anyscale 服务部署到生产环境#

对于生产环境,建议使用 Anyscale 服务将您的 Ray Serve 应用部署在专用集群上,而无需更改代码。Anyscale 提供可扩展性、容错能力和负载均衡,确保在节点故障、高流量和滚动更新时的弹性。请参阅 将小型 LLM 部署到生产环境,其中包含本教程中使用的Qwen2.5-VL-7B-Instruct等小型模型的示例。


限制每个提示的图像数量#

Ray Serve LLM 使用 vLLM 作为其后端引擎。您可以通过 Serve LLM 配置中的 engine_kwargs 部分传递参数来配置 vLLM。有关支持的选项的完整列表,请参阅 vLLM 文档

特别是,您可以通过在配置中设置 limit_mm_per_prompt 来限制每个请求的图像数量。

applications:
- ...
  args:
    llm_configs:
        ...
        engine_kwargs:
          ...
          limit_mm_per_prompt: {"image": 3}

总结#

在本教程中,您已从开发到生产部署了一个使用 Ray Serve LLM 的视觉 LLM。您学习了如何配置 Ray Serve LLM、在 Ray 集群上部署您的服务以及发送带图像的请求。