[Example][MiniCPM-o] Add offline/online MiniCPM-o 4.5 examples (#5222)

Signed-off-by: amy-why-3459 <wuhaiyan17@huawei.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
amy-why-3459andCursor authored and GitHub committed 2026-07-21 11:37:15 +08:00
1 parent dacb8e6f10
commit 64bcdc2186
9 files changed
+1174 -25

No files matched your search

+116 -23
View File
@@ -1,14 +1,19 @@
# vLLM-Omni · MiniCPM-o 4.5 Online Demo
# MiniCPM-o 4.5: Online serving
Gradio-based web UI for **MiniCPM-o 4.5** served via `vllm-omni`'s
OpenAI-compatible endpoints.
OpenAI-compatible `/v1/chat/completions` serving for **MiniCPM-o 4.5**, plus a
Gradio UI and curl / Python clients.
The UI supports:
Inputs: text / image / audio / video. Outputs: text and optional **24 kHz** speech.
- **Inputs**: text prompt + optional image, audio (file or mic), video.
- **Outputs**: text + speech (WAV player).
## Installation
## 1. Start the backend server
Please refer to [README.md](../../../README.md). Install the talker extra:
```bash
pip install 'vllm-omni[minicpmo]'
```
## Launch the server
The deploy config auto-loads via `--omni`; the default
`vllm_omni/deploy/minicpmo_4_5.yaml` targets a single-GPU layout (thinker
@@ -30,37 +35,125 @@ vllm serve openbmb/MiniCPM-o-4_5 --omni \
--host 0.0.0.0 --port 8099
```
Other layouts via `--deploy-config`:
Other layouts:
```bash
vllm serve openbmb/MiniCPM-o-4_5 --omni \
--deploy-config vllm_omni/deploy/minicpmo_4_5_8x4090.yaml \
--deploy-config vllm_omni/deploy/minicpmo_4_5_3gpu.yaml \
--trust-remote-code \
--host 0.0.0.0 --port 8099
```
## 2. Launch the Gradio demo
### Stage-based CLI (optional)
Stage 0 (thinker + API) and stage 1 (talker) can run in separate processes:
```bash
bash examples/online_serving/minicpmo/run_gradio_demo.sh
# Stage 0
CUDA_VISIBLE_DEVICES=0 vllm serve openbmb/MiniCPM-o-4_5 --omni \
--trust-remote-code --port 8099 --stage-id 0 \
--omni-master-address 127.0.0.1 --omni-master-port 26000
# Or run the python entry point directly:
python examples/online_serving/minicpmo/gradio_demo.py \
# Stage 1 (headless)
CUDA_VISIBLE_DEVICES=1 vllm serve openbmb/MiniCPM-o-4_5 --omni \
--trust-remote-code --stage-id 1 --headless \
--omni-master-address 127.0.0.1 --omni-master-port 26000
```
### Per-stage overrides
```bash
vllm serve openbmb/MiniCPM-o-4_5 --omni --trust-remote-code --port 8099 \
--stage-overrides '{"0": {"gpu_memory_utilization": 0.65}}'
```
## Send multimodal requests
```bash
cd examples/online_serving/minicpmo
```
### curl
```bash
bash run_curl_multimodal_generation.sh text
bash run_curl_multimodal_generation.sh use_image
bash run_curl_multimodal_generation.sh use_audio '["text"]' # text-only
```
Text + speech smoke test (TTS needs top-level `chat_template_kwargs`):
```bash
curl http://localhost:8099/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "openbmb/MiniCPM-o-4_5",
"messages": [{"role": "user", "content": "Say hello, then introduce vLLM in one sentence."}],
"modalities": ["text", "audio"],
"chat_template_kwargs": {"use_tts_template": true}
}'
```
### Python client
```bash
python openai_chat_completion_client_for_multimodal_generation.py \
--query-type use_image \
--port 8099 \
--host localhost
# Text-only (faster; no <|tts_bos|>)
python openai_chat_completion_client_for_multimodal_generation.py \
--query-type text \
--modalities text \
--prompt "Briefly introduce yourself."
```
Shared helpers also work if you pass MiniCPM defaults yourself:
```bash
python ../openai_chat_completion_client_for_multimodal_generation.py \
--model openbmb/MiniCPM-o-4_5 \
--query-type text \
--port 8099
```
(Note: the shared client does **not** set `use_tts_template`; prefer the
MiniCPM-specific client above for speech.)
### Gradio demo
```bash
bash run_gradio_demo.sh
# Or:
python gradio_demo.py \
--minicpmo45-api-base http://localhost:8099/v1 \
--minicpmo45-model openbmb/MiniCPM-o-4_5 \
--port 7862
```
Open `http://<host>:7862` in a browser.
Open `http://<host>:7862`. Uncheck **"Generate speech output (TTS)"** for
text-only responses.
## Modality control
| Modalities | Output |
|---|---|
| `["text"]` | Text only (no TTS bos) |
| `["text", "audio"]` / unset | Text + 24 kHz speech |
Speech requires `chat_template_kwargs.use_tts_template=true` so the chat
template appends `<|tts_bos|>`. For **curl**, put that field at the request
root; nested `extra_body` is ignored. The OpenAI Python SDK may use
`extra_body` because it merges those fields into the root.
## Notes
- **TTS trigger**: the demo sets
`extra_body.chat_template_kwargs.use_tts_template=True`, which appends
`<|tts_bos|>` to the assistant prefix.
- Uncheck **"Generate speech output (TTS)"** to get text-only responses
(faster).
- The audio output is the raw WAV returned by the stage-1 talker +
Token2Wav; sample rate is 24 kHz.
- Video input is forwarded as a base64 `video_url` entry; the server needs
decord/torchvision to decode it.
- Stage 1 is capped at `max_num_seqs: 1` in the deploy YAML (talker shares
request-0 audio metadata).
- Output audio is base64 WAV in `message.audio.data` (24 kHz mono).
- Offline counterpart:
[`examples/offline_inference/minicpmo/`](../../offline_inference/minicpmo/)
- Recipe:
[`recipes/OpenBMB/MiniCPM-o-4_5.md`](../../../recipes/OpenBMB/MiniCPM-o-4_5.md)
@@ -0,0 +1,237 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""OpenAI chat-completions client for MiniCPM-o 4.5 online serving.
Thin wrapper around the shared multimodal client helpers, with MiniCPM-specific
defaults (port 8099, system prompt, ``chat_template_kwargs.use_tts_template``).
"""
from __future__ import annotations
import base64
import concurrent.futures
import os
import sys
from openai import OpenAI
from vllm_omni.utils.tracking_parser import TrackingArgumentParser
# Reuse prompt builders / URL helpers from the shared online client.
_HERE = os.path.dirname(os.path.abspath(__file__))
_ONLINE_ROOT = os.path.abspath(os.path.join(_HERE, ".."))
if _ONLINE_ROOT not in sys.path:
sys.path.insert(0, _ONLINE_ROOT)
from openai_chat_completion_client_for_multimodal_generation import ( # noqa: E402
_build_prompt_for_query_type,
_parse_csv_arg,
make_audio_output_filename,
query_map,
)
SEED = 42
default_system = (
"You are MiniCPM-o, a helpful multimodal assistant that can "
"understand images, audio and video, and respond in text and speech."
)
def get_system_prompt() -> dict:
return {
"role": "system",
"content": [{"type": "text", "text": default_system}],
}
def _wants_tts(modalities: list[str] | None) -> bool:
if modalities is None:
return True
return "audio" in modalities
def run_multimodal_generation(args, client: OpenAI) -> None:
model_name = args.model
video_path = getattr(args, "video_path", None)
image_path = getattr(args, "image_path", None)
audio_path = getattr(args, "audio_path", None)
custom_prompt = getattr(args, "prompt", None)
if args.modalities is not None:
output_modalities = args.modalities.split(",")
else:
output_modalities = None
use_tts = _wants_tts(output_modalities)
num_concurrent_requests = args.num_concurrent_requests
prompt_list = _parse_csv_arg(getattr(args, "prompts", None))
request_payloads = []
for idx in range(num_concurrent_requests):
per_req_prompt = (
prompt_list[idx]
if idx < len(prompt_list)
else (custom_prompt if idx == 0 or not prompt_list else prompt_list[-1])
)
prompt = _build_prompt_for_query_type(
query_type=args.query_type,
custom_prompt=per_req_prompt,
video_path=video_path,
image_path=image_path,
audio_path=audio_path,
)
extra_body: dict = {
"chat_template_kwargs": {"use_tts_template": use_tts},
}
if args.query_type == "use_audio_in_video":
# MiniCPM-o 4.5 does not use Qwen's use_audio_in_video path; keep
# the flag only if the shared query type is selected explicitly.
extra_body["mm_processor_kwargs"] = {"use_audio_in_video": True}
request_payloads.append({"prompt": prompt, "extra_body": extra_body})
with concurrent.futures.ThreadPoolExecutor(max_workers=num_concurrent_requests) as executor:
futures = [
executor.submit(
client.chat.completions.create,
messages=[
get_system_prompt(),
payload["prompt"],
],
model=model_name,
modalities=output_modalities,
extra_body=payload["extra_body"],
stream=args.stream,
)
for payload in request_payloads
]
chat_completions = [future.result() for future in concurrent.futures.as_completed(futures)]
assert len(chat_completions) == num_concurrent_requests
count = 0
if not args.stream:
for chat_completion in chat_completions:
request_id = getattr(chat_completion, "id", None)
for choice in chat_completion.choices:
if choice.message.audio:
audio_data = base64.b64decode(choice.message.audio.data)
audio_file_path = make_audio_output_filename(request_id=request_id, index=count)
with open(audio_file_path, "wb") as f:
f.write(audio_data)
print(f"Audio saved to {audio_file_path}")
count += 1
elif choice.message.content:
print("Chat completion output from text:", choice.message.content)
else:
printed_content = False
for chat_completion in chat_completions:
for chunk in chat_completion:
for choice in chunk.choices:
if hasattr(choice, "delta"):
content = getattr(choice.delta, "content", None)
else:
content = None
if getattr(chunk, "modality", None) == "audio" and content:
audio_data = base64.b64decode(content)
request_id = getattr(chunk, "id", None)
audio_file_path = make_audio_output_filename(request_id=request_id, index=count)
with open(audio_file_path, "wb") as f:
f.write(audio_data)
print(f"\nAudio saved to {audio_file_path}")
count += 1
elif getattr(chunk, "modality", None) == "text":
if not printed_content:
printed_content = True
print("\ncontent:", end="", flush=True)
print(content, end="", flush=True)
def parse_args():
parser = TrackingArgumentParser(description="MiniCPM-o 4.5 online multimodal chat client")
parser.add_argument(
"--query-type",
"-q",
type=str,
default="text",
choices=query_map.keys(),
help="Query type.",
)
parser.add_argument(
"--model",
"-m",
type=str,
default="openbmb/MiniCPM-o-4_5",
help="Model Name / Path",
)
parser.add_argument(
"--video-path",
"-v",
type=str,
default=None,
help="Path to local video file or URL.",
)
parser.add_argument(
"--image-path",
"-i",
type=str,
default=None,
help="Path to local image file or URL.",
)
parser.add_argument(
"--audio-path",
"-a",
type=str,
default=None,
help="Path to local audio file or URL.",
)
parser.add_argument(
"--prompt",
"-p",
type=str,
default=None,
help="Custom text prompt/question.",
)
parser.add_argument(
"--modalities",
type=str,
default=None,
help="Output modalities, e.g. text or text,audio.",
)
parser.add_argument(
"--stream",
action="store_true",
help="Stream the response.",
)
parser.add_argument(
"--num-concurrent-requests",
type=int,
default=1,
help="Number of concurrent requests to send.",
)
parser.add_argument(
"--port",
type=int,
default=8099,
help="Port of the vLLM Omni API server.",
)
parser.add_argument(
"--host",
type=str,
default="localhost",
help="Host/IP of the vLLM Omni API server.",
)
parser.add_argument(
"--prompts",
type=str,
default=None,
help="Comma-separated prompts for concurrent requests.",
)
return parser.parse_args()
if __name__ == "__main__":
args = parse_args()
openai_api_base = f"http://{args.host}:{args.port}/v1"
client = OpenAI(api_key="EMPTY", base_url=openai_api_base)
run_multimodal_generation(args, client)
@@ -0,0 +1,154 @@
#!/usr/bin/env bash
set -euo pipefail
# Default query type
QUERY_TYPE="${1:-text}"
# Default modalities argument (JSON). Use null for server default (text+audio).
MODALITIES="${2:-null}"
# Validate query type
if [[ ! "$QUERY_TYPE" =~ ^(text|use_audio|use_image|use_video)$ ]]; then
echo "Error: Invalid query type '$QUERY_TYPE'"
echo "Usage: $0 [text|use_audio|use_image|use_video] [modalities]"
echo " text: Text query"
echo " use_audio: Audio + text query"
echo " use_image: Image + text query"
echo " use_video: Video + text query"
echo " modalities: JSON list or null (default: null → text+audio)"
echo " examples: '[\"text\"]' '[\"text\",\"audio\"]'"
exit 1
fi
HOST="${HOST:-localhost}"
PORT="${PORT:-8099}"
MODEL="${MODEL:-openbmb/MiniCPM-o-4_5}"
thinker_sampling_params='{
"temperature": 0.0,
"top_p": 1.0,
"top_k": -1,
"max_tokens": 2048,
"seed": 42,
"detokenize": true,
"repetition_penalty": 1.1
}'
talker_sampling_params='{
"temperature": 0.0,
"top_p": 1.0,
"top_k": -1,
"max_tokens": 1,
"seed": 42,
"detokenize": false
}'
# Above is optional; defaults live in vllm_omni/deploy/minicpmo_4_5.yaml.
MARY_HAD_LAMB_AUDIO_URL="https://vllm-public-assets.s3.us-west-2.amazonaws.com/multimodal_asset/mary_had_lamb.ogg"
CHERRY_BLOSSOM_IMAGE_URL="https://vllm-public-assets.s3.us-west-2.amazonaws.com/vision_model_images/cherry_blossom.jpg"
SAMPLE_VIDEO_URL="https://huggingface.co/datasets/raushan-testing-hf/videos-test/resolve/main/sample_demo_1.mp4"
case "$QUERY_TYPE" in
text)
user_content='[
{
"type": "text",
"text": "Say hello, then introduce vLLM-Omni in one sentence."
}
]'
;;
use_audio)
user_content='[
{
"type": "audio_url",
"audio_url": {
"url": "'"$MARY_HAD_LAMB_AUDIO_URL"'"
}
},
{
"type": "text",
"text": "What is the content of this audio?"
}
]'
;;
use_image)
user_content='[
{
"type": "image_url",
"image_url": {
"url": "'"$CHERRY_BLOSSOM_IMAGE_URL"'"
}
},
{
"type": "text",
"text": "What is the content of this image?"
}
]'
;;
use_video)
user_content='[
{
"type": "video_url",
"video_url": {
"url": "'"$SAMPLE_VIDEO_URL"'"
}
},
{
"type": "text",
"text": "Why is this video funny?"
}
]'
;;
esac
sampling_params_list='[
'"$thinker_sampling_params"',
'"$talker_sampling_params"'
]'
# TTS speech path needs use_tts_template at the request root (curl does not
# flatten nested extra_body). Skip it when the caller asked for text-only.
USE_TTS_TEMPLATE=true
if [[ "$MODALITIES" == '["text"]' || "$MODALITIES" == "['text']" ]]; then
USE_TTS_TEMPLATE=false
fi
echo "Running query type: $QUERY_TYPE (host=$HOST port=$PORT model=$MODEL)"
echo "modalities=$MODALITIES use_tts_template=$USE_TTS_TEMPLATE"
echo ""
request_body=$(cat <<EOF
{
"model": "$MODEL",
"sampling_params_list": $sampling_params_list,
"modalities": $MODALITIES,
"chat_template_kwargs": {"use_tts_template": $USE_TTS_TEMPLATE},
"messages": [
{
"role": "system",
"content": [
{
"type": "text",
"text": "You are MiniCPM-o, a helpful multimodal assistant that can understand images, audio and video, and respond in text and speech."
}
]
},
{
"role": "user",
"content": $user_content
}
]
}
EOF
)
output=$(curl -sS --retry 3 --retry-delay 3 --retry-connrefused \
-X POST "http://${HOST}:${PORT}/v1/chat/completions" \
-H "Content-Type: application/json" \
-d "$request_body")
# Text content of the first choice only (audio is base64 WAV and too large to print).
echo "Output of request: $(echo "$output" | jq -r '.choices[0].message.content // .error // .')"
# Indicate whether any choice carried audio.
has_audio=$(echo "$output" | jq '[.choices[]? | select(.message.audio != null)] | length')
echo "Choices with audio: ${has_audio}"