[Feature]Basic version of supporting streaming output (#367)
Signed-off-by: Gaohan123 <hgaoaf@connect.ust.hk>
This commit is contained in:
1 parent
c94ce4d85f
commit
9c7de5373a
41 files changed
+1567
-243
No files matched your search
@@ -63,6 +63,7 @@ from PIL import Image
|
||||
|
||||
from vllm_omni.diffusion.data import DiffusionParallelConfig, logger
|
||||
from vllm_omni.entrypoints.omni import Omni
|
||||
from vllm_omni.outputs import OmniRequestOutput
|
||||
from vllm_omni.utils.platform_utils import detect_device_type, is_npu
|
||||
|
||||
|
||||
@@ -340,21 +341,23 @@ def main():
|
||||
# Print profiling results
|
||||
print(f"Total generation time: {generation_time:.4f} seconds ({generation_time * 1000:.2f} ms)")
|
||||
|
||||
# omni.generate() returns Generator[OmniRequestOutput, None, None], convert to list
|
||||
outputs = list(outputs)
|
||||
if not outputs:
|
||||
raise ValueError("No output generated from omni.generate()")
|
||||
logger.info("Outputs: %s", outputs)
|
||||
|
||||
# Extract images from OmniRequestOutput
|
||||
# omni.generate() returns list[OmniRequestOutput], extract images from request_output[0]['images']
|
||||
# omni.generate() returns Generator[OmniRequestOutput, None, None], extract images from request_output[0].images
|
||||
first_output = outputs[0]
|
||||
if not hasattr(first_output, "request_output") or not first_output.request_output:
|
||||
raise ValueError("No request_output found in OmniRequestOutput")
|
||||
|
||||
req_out = first_output.request_output[0]
|
||||
if not isinstance(req_out, dict) or "images" not in req_out:
|
||||
if not isinstance(req_out, OmniRequestOutput) or not hasattr(req_out, "images"):
|
||||
raise ValueError("Invalid request_output structure or missing 'images' key")
|
||||
|
||||
images = req_out["images"]
|
||||
images = req_out.images
|
||||
if not images:
|
||||
raise ValueError("No images found in request_output")
|
||||
|
||||
|
||||
@@ -16,11 +16,11 @@ Then run:
|
||||
|
||||
```bash
|
||||
python image_edit.py \
|
||||
--image qwen_bear.png \
|
||||
--image qwen-bear.png \
|
||||
--prompt "Let this mascot dance under the moon, surrounded by floating stars and poetic bubbles such as 'Be Kind'" \
|
||||
--output output_image_edit.png \
|
||||
--num_inference_steps 50 \
|
||||
--cfg_scale 4.0 \
|
||||
--cfg_scale 4.0
|
||||
```
|
||||
|
||||
### Multiple Image Editing (Qwen-Image-Edit-2509)
|
||||
|
||||
@@ -26,6 +26,7 @@ import PIL.Image
|
||||
import torch
|
||||
|
||||
from vllm_omni.entrypoints.omni import Omni
|
||||
from vllm_omni.outputs import OmniRequestOutput
|
||||
from vllm_omni.utils.platform_utils import detect_device_type, is_npu
|
||||
|
||||
|
||||
@@ -102,6 +103,7 @@ def main():
|
||||
flow_shift=args.flow_shift,
|
||||
)
|
||||
|
||||
# omni.generate() returns Generator[OmniRequestOutput, None, None]
|
||||
frames = omni.generate(
|
||||
args.prompt,
|
||||
negative_prompt=args.negative_prompt,
|
||||
@@ -115,6 +117,32 @@ def main():
|
||||
num_frames=args.num_frames,
|
||||
)
|
||||
|
||||
# Extract video frames from OmniRequestOutput
|
||||
frames = list(frames)
|
||||
if isinstance(frames, list) and len(frames) > 0:
|
||||
first_item = frames[0]
|
||||
|
||||
# Check if it's an OmniRequestOutput
|
||||
if hasattr(first_item, "final_output_type"):
|
||||
if first_item.final_output_type != "image":
|
||||
raise ValueError(
|
||||
f"Unexpected output type '{first_item.final_output_type}', expected 'image' for video generation."
|
||||
)
|
||||
|
||||
# Pipeline mode: extract from nested request_output
|
||||
if hasattr(first_item, "is_pipeline_output") and first_item.is_pipeline_output:
|
||||
if isinstance(first_item.request_output, list) and len(first_item.request_output) > 0:
|
||||
inner_output = first_item.request_output[0]
|
||||
if isinstance(inner_output, OmniRequestOutput) and hasattr(inner_output, "images"):
|
||||
frames = inner_output.images[0] if inner_output.images else None
|
||||
if frames is None:
|
||||
raise ValueError("No video frames found in output.")
|
||||
# Diffusion mode: use direct images field
|
||||
elif hasattr(first_item, "images") and first_item.images:
|
||||
frames = first_item.images
|
||||
else:
|
||||
raise ValueError("No video frames found in OmniRequestOutput.")
|
||||
|
||||
output_path = Path(args.output)
|
||||
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
|
||||
@@ -376,12 +376,12 @@ def main(args):
|
||||
for i, prompt in enumerate(prompts):
|
||||
prompt["modalities"] = output_modalities
|
||||
|
||||
omni_outputs = omni_llm.generate(prompts, sampling_params_list)
|
||||
omni_generator = omni_llm.generate(prompts, sampling_params_list)
|
||||
|
||||
# Determine output directory: prefer --output-dir; fallback to --output-wav
|
||||
output_dir = args.output_dir if getattr(args, "output_dir", None) else args.output_wav
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
for stage_outputs in omni_outputs:
|
||||
for stage_outputs in omni_generator:
|
||||
if stage_outputs.final_output_type == "text":
|
||||
for output in stage_outputs.request_output:
|
||||
request_id = output.request_id
|
||||
|
||||
@@ -319,12 +319,12 @@ def main(args):
|
||||
for i, prompt in enumerate(prompts):
|
||||
prompt["modalities"] = output_modalities
|
||||
|
||||
omni_outputs = omni_llm.generate(prompts, sampling_params_list)
|
||||
omni_generator = omni_llm.generate(prompts, sampling_params_list)
|
||||
# Determine output directory: prefer --output-dir; fallback to --output-wav
|
||||
output_dir = args.output_dir if getattr(args, "output_dir", None) else args.output_wav
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
|
||||
for stage_outputs in omni_outputs:
|
||||
for stage_outputs in omni_generator:
|
||||
if stage_outputs.final_output_type == "text":
|
||||
for output in stage_outputs.request_output:
|
||||
request_id = output.request_id
|
||||
|
||||
@@ -16,7 +16,7 @@ if __name__ == "__main__":
|
||||
omni = Omni(model="Qwen/Qwen-Image")
|
||||
prompt = "a cup of coffee on the table"
|
||||
outputs = omni.generate(prompt)
|
||||
images = outputs[0].request_output[0]["images"]
|
||||
images = list(outputs)[0].request_output[0].images
|
||||
images[0].save("coffee.png")
|
||||
```
|
||||
|
||||
@@ -34,7 +34,7 @@ if __name__ == "__main__":
|
||||
]
|
||||
outputs = omni.generate(prompts)
|
||||
for i, output in enumerate(outputs):
|
||||
image = output.request_output[0]["images"][0].save(f"{i}.jpg")
|
||||
image = output.request_output[0].images[0].save(f"{i}.jpg")
|
||||
```
|
||||
|
||||
## Local CLI Usage
|
||||
|
||||
@@ -5,6 +5,7 @@ import gradio as gr
|
||||
import torch
|
||||
|
||||
from vllm_omni.entrypoints.omni import Omni
|
||||
from vllm_omni.outputs import OmniRequestOutput
|
||||
from vllm_omni.utils.platform_utils import detect_device_type, is_npu
|
||||
|
||||
ASPECT_RATIOS: dict[str, tuple[int, int]] = {
|
||||
@@ -98,7 +99,7 @@ def build_demo(args: argparse.Namespace) -> gr.Blocks:
|
||||
if num_images not in {1, 2, 3, 4}:
|
||||
raise gr.Error("Number of images must be 1, 2, 3, or 4.")
|
||||
generator = torch.Generator(device=device).manual_seed(seed)
|
||||
images = omni.generate(
|
||||
outputs = omni.generate(
|
||||
prompt.strip(),
|
||||
height=height,
|
||||
width=width,
|
||||
@@ -107,7 +108,20 @@ def build_demo(args: argparse.Namespace) -> gr.Blocks:
|
||||
num_inference_steps=num_steps,
|
||||
num_outputs_per_prompt=num_images,
|
||||
)
|
||||
return [img for img in images[:num_images]]
|
||||
images_outputs = []
|
||||
for output in outputs:
|
||||
req_out = output.request_output[0]
|
||||
if not isinstance(req_out, OmniRequestOutput) or not hasattr(req_out, "images"):
|
||||
raise ValueError("Invalid request_output structure or missing 'images' key")
|
||||
images = req_out.images
|
||||
if not images:
|
||||
raise ValueError("No images found in request_output")
|
||||
# Extend the list with individual images (not append the entire list)
|
||||
images_outputs.extend(images)
|
||||
if len(images_outputs) >= num_images:
|
||||
break
|
||||
# Return only the requested number of images
|
||||
return images_outputs[:num_images]
|
||||
|
||||
with gr.Blocks(
|
||||
title="vLLM-Omni Web Serving Demo",
|
||||
|
||||
@@ -9,6 +9,7 @@ import torch
|
||||
|
||||
from vllm_omni.diffusion.data import DiffusionParallelConfig, logger
|
||||
from vllm_omni.entrypoints.omni import Omni
|
||||
from vllm_omni.outputs import OmniRequestOutput
|
||||
from vllm_omni.utils.platform_utils import detect_device_type, is_npu
|
||||
|
||||
|
||||
@@ -144,8 +145,9 @@ def main():
|
||||
print(f"Total generation time: {generation_time:.4f} seconds ({generation_time * 1000:.2f} ms)")
|
||||
|
||||
# Extract images from OmniRequestOutput
|
||||
# omni.generate() returns list[OmniRequestOutput], extract images from the first output
|
||||
if not outputs or len(outputs) == 0:
|
||||
# omni.generate() returns Generator[OmniRequestOutput, None, None], convert to list
|
||||
outputs = list(outputs)
|
||||
if not outputs:
|
||||
raise ValueError("No output generated from omni.generate()")
|
||||
logger.info(f"Outputs: {outputs}")
|
||||
|
||||
@@ -155,10 +157,10 @@ def main():
|
||||
raise ValueError("No request_output found in OmniRequestOutput")
|
||||
|
||||
req_out = first_output.request_output[0]
|
||||
if not isinstance(req_out, dict) or "images" not in req_out:
|
||||
if not isinstance(req_out, OmniRequestOutput) or not hasattr(req_out, "images"):
|
||||
raise ValueError("Invalid request_output structure or missing 'images' key")
|
||||
|
||||
images = req_out["images"]
|
||||
images = req_out.images
|
||||
if not images:
|
||||
raise ValueError("No images found in request_output")
|
||||
|
||||
@@ -175,8 +177,6 @@ def main():
|
||||
img.save(save_path)
|
||||
print(f"Saved generated image to {save_path}")
|
||||
|
||||
omni.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -8,6 +8,7 @@ import numpy as np
|
||||
import torch
|
||||
|
||||
from vllm_omni.entrypoints.omni import Omni
|
||||
from vllm_omni.outputs import OmniRequestOutput
|
||||
from vllm_omni.utils.platform_utils import detect_device_type, is_npu
|
||||
|
||||
|
||||
@@ -53,6 +54,7 @@ def main():
|
||||
flow_shift=args.flow_shift,
|
||||
)
|
||||
|
||||
# omni.generate() returns Generator[OmniRequestOutput, None, None]
|
||||
frames = omni.generate(
|
||||
args.prompt,
|
||||
negative_prompt=args.negative_prompt,
|
||||
@@ -65,6 +67,32 @@ def main():
|
||||
num_frames=args.num_frames,
|
||||
)
|
||||
|
||||
# Extract video frames from OmniRequestOutput
|
||||
frames = list(frames)
|
||||
if isinstance(frames, list) and len(frames) > 0:
|
||||
first_item = frames[0]
|
||||
|
||||
# Check if it's an OmniRequestOutput
|
||||
if hasattr(first_item, "final_output_type"):
|
||||
if first_item.final_output_type != "image":
|
||||
raise ValueError(
|
||||
f"Unexpected output type '{first_item.final_output_type}', expected 'image' for video generation."
|
||||
)
|
||||
|
||||
# Pipeline mode: extract from nested request_output
|
||||
if hasattr(first_item, "is_pipeline_output") and first_item.is_pipeline_output:
|
||||
if isinstance(first_item.request_output, list) and len(first_item.request_output) > 0:
|
||||
inner_output = first_item.request_output[0]
|
||||
if isinstance(inner_output, OmniRequestOutput) and hasattr(inner_output, "images"):
|
||||
frames = inner_output.images[0] if inner_output.images else None
|
||||
if frames is None:
|
||||
raise ValueError("No video frames found in output.")
|
||||
# Diffusion mode: use direct images field
|
||||
elif hasattr(first_item, "images") and first_item.images:
|
||||
frames = first_item.images
|
||||
else:
|
||||
raise ValueError("No video frames found in OmniRequestOutput.")
|
||||
|
||||
output_path = Path(args.output)
|
||||
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
try:
|
||||
|
||||
@@ -57,13 +57,92 @@ bash run_curl_multimodal_generation.sh mixed_modalities
|
||||
```
|
||||
|
||||
## Modality control
|
||||
If you want to control output modalities, e.g. only output text, you can run the command below:
|
||||
You can control output modalities to specify which types of output the model should generate. This is useful when you only need text output and want to skip audio generation stages for better performance.
|
||||
|
||||
### Supported modalities
|
||||
|
||||
| Modalities | Output |
|
||||
|------------|--------|
|
||||
| `["text"]` | Text only |
|
||||
| `["audio"]` | Text + Audio |
|
||||
| `["text", "audio"]` | Text + Audio |
|
||||
| Not specified | Text + Audio (default) |
|
||||
|
||||
### Using curl
|
||||
|
||||
#### Text only
|
||||
|
||||
```bash
|
||||
curl http://localhost:8091/v1/chat/completions \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"model": "Qwen/Qwen2.5-Omni-7B",
|
||||
"messages": [{"role": "user", "content": "Describe vLLM in brief."}],
|
||||
"modalities": ["text"]
|
||||
}'
|
||||
```
|
||||
|
||||
#### Text + Audio
|
||||
|
||||
```bash
|
||||
curl http://localhost:8091/v1/chat/completions \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"model": "Qwen/Qwen2.5-Omni-7B",
|
||||
"messages": [{"role": "user", "content": "Describe vLLM in brief."}],
|
||||
"modalities": ["audio"]
|
||||
}'
|
||||
```
|
||||
|
||||
### Using Python client
|
||||
|
||||
```bash
|
||||
python openai_chat_completion_client_for_multimodal_generation.py \
|
||||
--query-type mixed_modalities \
|
||||
--modalities text
|
||||
```
|
||||
|
||||
### Using OpenAI Python SDK
|
||||
|
||||
#### Text only
|
||||
|
||||
```python
|
||||
from openai import OpenAI
|
||||
|
||||
client = OpenAI(base_url="http://localhost:8091/v1", api_key="EMPTY")
|
||||
|
||||
response = client.chat.completions.create(
|
||||
model="Qwen/Qwen2.5-Omni-7B",
|
||||
messages=[{"role": "user", "content": "Describe vLLM in brief."}],
|
||||
modalities=["text"]
|
||||
)
|
||||
print(response.choices[0].message.content)
|
||||
```
|
||||
|
||||
#### Text + Audio
|
||||
|
||||
```python
|
||||
from openai import OpenAI
|
||||
|
||||
client = OpenAI(base_url="http://localhost:8091/v1", api_key="EMPTY")
|
||||
|
||||
response = client.chat.completions.create(
|
||||
model="Qwen/Qwen2.5-Omni-7B",
|
||||
messages=[{"role": "user", "content": "Describe vLLM in brief."}],
|
||||
modalities=["audio"]
|
||||
)
|
||||
# Response contains two choices: one with text, one with audio
|
||||
print(response.choices[0].message.content) # Text response
|
||||
print(response.choices[1].message.audio) # Audio response
|
||||
|
||||
## Streaming Output
|
||||
If you want to enable streaming output, please set the argument as below. The final output will be obtained just after generated by corresponding stage. Now we only support text streaming output. Other modalities can output normally.
|
||||
```bash
|
||||
python openai_chat_completion_client_for_multimodal_generation.py \
|
||||
--query-type mixed_modalities \
|
||||
--stream
|
||||
```
|
||||
|
||||
## Run Local Web UI Demo
|
||||
|
||||
This Web UI demo allows users to interact with the model through a web browser.
|
||||
|
||||
@@ -23,16 +23,18 @@ SUPPORTED_MODELS: dict[str, dict[str, Any]] = {
|
||||
"top_p": 1.0,
|
||||
"top_k": -1,
|
||||
"max_tokens": 2048,
|
||||
"seed": SEED,
|
||||
"detokenize": True,
|
||||
"repetition_penalty": 1.1,
|
||||
},
|
||||
"talker": {
|
||||
"temperature": 0.0,
|
||||
"top_p": 1.0,
|
||||
"top_k": -1,
|
||||
"temperature": 0.9,
|
||||
"top_p": 0.8,
|
||||
"top_k": 40,
|
||||
"max_tokens": 2048,
|
||||
"seed": SEED,
|
||||
"detokenize": True,
|
||||
"repetition_penalty": 1.1,
|
||||
"repetition_penalty": 1.05,
|
||||
"stop_token_ids": [8294],
|
||||
},
|
||||
"code2wav": {
|
||||
@@ -40,6 +42,7 @@ SUPPORTED_MODELS: dict[str, dict[str, Any]] = {
|
||||
"top_p": 1.0,
|
||||
"top_k": -1,
|
||||
"max_tokens": 2048,
|
||||
"seed": SEED,
|
||||
"detokenize": True,
|
||||
"repetition_penalty": 1.1,
|
||||
},
|
||||
@@ -241,10 +244,12 @@ def run_inference_api(
|
||||
video_file: str | None = None,
|
||||
use_audio_in_video: bool = False,
|
||||
output_modalities: str | None = None,
|
||||
stream: bool = False,
|
||||
):
|
||||
"""Run inference using OpenAI API client with multimodal support."""
|
||||
if not user_prompt.strip() and not audio_file and not image_file and not video_file:
|
||||
return "Please provide at least a text prompt or multimodal input.", None
|
||||
yield "Please provide at least a text prompt or multimodal input.", None
|
||||
return
|
||||
|
||||
try:
|
||||
# Build message content list
|
||||
@@ -324,7 +329,7 @@ def run_inference_api(
|
||||
extra_body["mm_processor_kwargs"] = mm_processor_kwargs
|
||||
|
||||
# Parse output modalities
|
||||
if output_modalities is not None:
|
||||
if output_modalities and output_modalities.strip():
|
||||
output_modalities_list = [m.strip() for m in output_modalities.split(",")]
|
||||
else:
|
||||
output_modalities_list = None
|
||||
@@ -335,29 +340,71 @@ def run_inference_api(
|
||||
model=model,
|
||||
modalities=output_modalities_list,
|
||||
extra_body=extra_body,
|
||||
stream=stream,
|
||||
)
|
||||
|
||||
# Extract outputs
|
||||
text_outputs: list[str] = []
|
||||
audio_output = None
|
||||
if not stream:
|
||||
# Non-streaming mode: extract outputs and yield once
|
||||
text_outputs: list[str] = []
|
||||
audio_output = None
|
||||
|
||||
for choice in chat_completion.choices:
|
||||
if choice.message.content:
|
||||
text_outputs.append(choice.message.content)
|
||||
if choice.message.audio:
|
||||
# Decode base64 audio
|
||||
audio_data = base64.b64decode(choice.message.audio.data)
|
||||
# Load audio from bytes
|
||||
audio_np, sample_rate = sf.read(io.BytesIO(audio_data))
|
||||
# Convert to mono if needed
|
||||
if audio_np.ndim > 1:
|
||||
audio_np = audio_np[:, 0]
|
||||
audio_output = (int(sample_rate), audio_np.astype(np.float32))
|
||||
for choice in chat_completion.choices:
|
||||
if choice.message.content:
|
||||
text_outputs.append(choice.message.content)
|
||||
if choice.message.audio:
|
||||
# Decode base64 audio
|
||||
audio_data = base64.b64decode(choice.message.audio.data)
|
||||
# Load audio from bytes
|
||||
audio_np, sample_rate = sf.read(io.BytesIO(audio_data))
|
||||
# Convert to mono if needed
|
||||
if audio_np.ndim > 1:
|
||||
audio_np = audio_np[:, 0]
|
||||
audio_output = (int(sample_rate), audio_np.astype(np.float32))
|
||||
|
||||
text_response = "\n\n".join(text_outputs) if text_outputs else "No text output."
|
||||
yield text_response, audio_output
|
||||
else:
|
||||
# Streaming mode: yield incremental updates
|
||||
text_content = ""
|
||||
audio_output = None
|
||||
|
||||
for chunk in chat_completion:
|
||||
for choice in chunk.choices:
|
||||
if hasattr(choice, "delta"):
|
||||
content = getattr(choice.delta, "content", None)
|
||||
else:
|
||||
content = None
|
||||
|
||||
# Handle audio modality
|
||||
if getattr(chunk, "modality", None) == "audio" and content:
|
||||
try:
|
||||
# Decode base64 audio
|
||||
audio_data = base64.b64decode(content)
|
||||
# Load audio from bytes
|
||||
audio_np, sample_rate = sf.read(io.BytesIO(audio_data))
|
||||
# Convert to mono if needed
|
||||
if audio_np.ndim > 1:
|
||||
audio_np = audio_np[:, 0]
|
||||
audio_output = (int(sample_rate), audio_np.astype(np.float32))
|
||||
# Yield current text and audio
|
||||
yield text_content if text_content else "", audio_output
|
||||
except Exception: # pylint: disable=broad-except
|
||||
# If audio processing fails, just yield text
|
||||
yield text_content if text_content else "", None
|
||||
|
||||
# Handle text modality
|
||||
elif getattr(chunk, "modality", None) == "text":
|
||||
if content:
|
||||
text_content += content
|
||||
# Yield updated text content (keep existing audio if any)
|
||||
yield text_content, audio_output
|
||||
|
||||
# Final yield with accumulated text and last audio (if any)
|
||||
yield text_content if text_content else "No text output.", audio_output
|
||||
|
||||
text_response = "\n\n".join(text_outputs) if text_outputs else "No text output."
|
||||
return text_response, audio_output
|
||||
except Exception as exc: # pylint: disable=broad-except
|
||||
return f"Inference failed: {exc}", None
|
||||
error_msg = f"Inference failed: {exc}"
|
||||
yield error_msg, None
|
||||
|
||||
|
||||
def build_interface(
|
||||
@@ -374,8 +421,10 @@ def build_interface(
|
||||
video_file: str | None,
|
||||
use_audio_in_video: bool,
|
||||
output_modalities: str | None = None,
|
||||
stream: bool = False,
|
||||
):
|
||||
return run_inference_api(
|
||||
# Always yield from the API function to maintain consistent generator behavior
|
||||
yield from run_inference_api(
|
||||
client,
|
||||
model,
|
||||
sampling_params_dict,
|
||||
@@ -385,6 +434,7 @@ def build_interface(
|
||||
video_file,
|
||||
use_audio_in_video,
|
||||
output_modalities,
|
||||
stream,
|
||||
)
|
||||
|
||||
css = """
|
||||
@@ -455,8 +505,15 @@ def build_interface(
|
||||
with gr.Row():
|
||||
output_modalities = gr.Textbox(
|
||||
label="Output Modalities",
|
||||
value=None,
|
||||
placeholder="For example: text, image, video. Use comma to separate multiple modalities.",
|
||||
lines=1,
|
||||
scale=2,
|
||||
)
|
||||
stream_checkbox = gr.Checkbox(
|
||||
label="Stream output",
|
||||
value=False,
|
||||
info="Enable streaming to see output as it's generated.",
|
||||
scale=1,
|
||||
)
|
||||
|
||||
@@ -474,7 +531,15 @@ def build_interface(
|
||||
|
||||
generate_btn.click(
|
||||
fn=run_inference,
|
||||
inputs=[input_box, audio_input, image_input, video_input, use_audio_in_video_checkbox, output_modalities],
|
||||
inputs=[
|
||||
input_box,
|
||||
audio_input,
|
||||
image_input,
|
||||
video_input,
|
||||
use_audio_in_video_checkbox,
|
||||
output_modalities,
|
||||
stream_checkbox,
|
||||
],
|
||||
outputs=[text_output, audio_output],
|
||||
)
|
||||
demo.queue()
|
||||
|
||||
+39
-10
@@ -354,19 +354,43 @@ def run_multimodal_generation(args) -> None:
|
||||
model=model_name,
|
||||
modalities=output_modalities,
|
||||
extra_body=extra_body,
|
||||
stream=args.stream,
|
||||
)
|
||||
|
||||
count = 0
|
||||
for choice in chat_completion.choices:
|
||||
if choice.message.audio:
|
||||
audio_data = base64.b64decode(choice.message.audio.data)
|
||||
audio_file_path = f"audio_{count}.wav"
|
||||
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)
|
||||
if not args.stream:
|
||||
for choice in chat_completion.choices:
|
||||
if choice.message.audio:
|
||||
audio_data = base64.b64decode(choice.message.audio.data)
|
||||
audio_file_path = f"audio_{count}.wav"
|
||||
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 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)
|
||||
audio_file_path = f"audio_{count}.wav"
|
||||
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():
|
||||
@@ -413,6 +437,11 @@ def parse_args():
|
||||
default=None,
|
||||
help="Output modalities to use for the prompts.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--stream",
|
||||
action="store_true",
|
||||
help="Stream the response.",
|
||||
)
|
||||
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
@@ -65,13 +65,92 @@ sudo apt install ffmpeg
|
||||
```
|
||||
|
||||
## Modality control
|
||||
If you want to control output modalities, e.g. only output text, you can run the command below:
|
||||
You can control output modalities to specify which types of output the model should generate. This is useful when you only need text output and want to skip audio generation stages for better performance.
|
||||
|
||||
### Supported modalities
|
||||
|
||||
| Modalities | Output |
|
||||
|------------|--------|
|
||||
| `["text"]` | Text only |
|
||||
| `["audio"]` | Text + Audio |
|
||||
| `["text", "audio"]` | Text + Audio |
|
||||
| Not specified | Text + Audio (default) |
|
||||
|
||||
### Using curl
|
||||
|
||||
#### Text only
|
||||
|
||||
```bash
|
||||
curl http://localhost:8091/v1/chat/completions \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"model": "Qwen/Qwen3-Omni-30B-A3B-Instruct",
|
||||
"messages": [{"role": "user", "content": "Describe vLLM in brief."}],
|
||||
"modalities": ["text"]
|
||||
}'
|
||||
```
|
||||
|
||||
#### Text + Audio
|
||||
|
||||
```bash
|
||||
curl http://localhost:8091/v1/chat/completions \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"model": "Qwen/Qwen3-Omni-30B-A3B-Instruct",
|
||||
"messages": [{"role": "user", "content": "Describe vLLM in brief."}],
|
||||
"modalities": ["audio"]
|
||||
}'
|
||||
```
|
||||
|
||||
### Using Python client
|
||||
|
||||
```bash
|
||||
python openai_chat_completion_client_for_multimodal_generation.py \
|
||||
--query-type use_image \
|
||||
--modalities text
|
||||
```
|
||||
|
||||
### Using OpenAI Python SDK
|
||||
|
||||
#### Text only
|
||||
|
||||
```python
|
||||
from openai import OpenAI
|
||||
|
||||
client = OpenAI(base_url="http://localhost:8091/v1", api_key="EMPTY")
|
||||
|
||||
response = client.chat.completions.create(
|
||||
model="Qwen/Qwen3-Omni-30B-A3B-Instruct",
|
||||
messages=[{"role": "user", "content": "Describe vLLM in brief."}],
|
||||
modalities=["text"]
|
||||
)
|
||||
print(response.choices[0].message.content)
|
||||
```
|
||||
|
||||
#### Text + Audio
|
||||
|
||||
```python
|
||||
from openai import OpenAI
|
||||
|
||||
client = OpenAI(base_url="http://localhost:8091/v1", api_key="EMPTY")
|
||||
|
||||
response = client.chat.completions.create(
|
||||
model="Qwen/Qwen3-Omni-30B-A3B-Instruct",
|
||||
messages=[{"role": "user", "content": "Describe vLLM in brief."}],
|
||||
modalities=["audio"]
|
||||
)
|
||||
# Response contains two choices: one with text, one with audio
|
||||
print(response.choices[0].message.content) # Text response
|
||||
print(response.choices[1].message.audio) # Audio response
|
||||
|
||||
## Streaming Output
|
||||
If you want to enable streaming output, please set the argument as below. The final output will be obtained just after generated by corresponding stage. Now we only support text streaming output. Other modalities can output normally.
|
||||
```bash
|
||||
python openai_chat_completion_client_for_multimodal_generation.py \
|
||||
--query-type use_image \
|
||||
--stream
|
||||
```
|
||||
|
||||
## Run Local Web UI Demo
|
||||
|
||||
This Web UI demo allows users to interact with the model through a web browser.
|
||||
|
||||
@@ -244,10 +244,11 @@ def run_inference_api(
|
||||
video_file: str | None = None,
|
||||
use_audio_in_video: bool = False,
|
||||
output_modalities: str | None = None,
|
||||
stream: bool = False,
|
||||
):
|
||||
"""Run inference using OpenAI API client with multimodal support."""
|
||||
if not user_prompt.strip() and not audio_file and not image_file and not video_file:
|
||||
return "Please provide at least a text prompt or multimodal input.", None
|
||||
yield "Please provide at least a text prompt or multimodal input.", None
|
||||
|
||||
try:
|
||||
# Build message content list
|
||||
@@ -327,7 +328,7 @@ def run_inference_api(
|
||||
extra_body["mm_processor_kwargs"] = mm_processor_kwargs
|
||||
|
||||
# Parse output modalities
|
||||
if output_modalities is not None:
|
||||
if output_modalities and output_modalities.strip():
|
||||
output_modalities_list = [m.strip() for m in output_modalities.split(",")]
|
||||
else:
|
||||
output_modalities_list = None
|
||||
@@ -338,29 +339,71 @@ def run_inference_api(
|
||||
model=model,
|
||||
modalities=output_modalities_list,
|
||||
extra_body=extra_body,
|
||||
stream=stream,
|
||||
)
|
||||
|
||||
# Extract outputs
|
||||
text_outputs: list[str] = []
|
||||
audio_output = None
|
||||
if not stream:
|
||||
# Non-streaming mode: extract outputs and yield once
|
||||
text_outputs: list[str] = []
|
||||
audio_output = None
|
||||
|
||||
for choice in chat_completion.choices:
|
||||
if choice.message.content:
|
||||
text_outputs.append(choice.message.content)
|
||||
if choice.message.audio:
|
||||
# Decode base64 audio
|
||||
audio_data = base64.b64decode(choice.message.audio.data)
|
||||
# Load audio from bytes
|
||||
audio_np, sample_rate = sf.read(io.BytesIO(audio_data))
|
||||
# Convert to mono if needed
|
||||
if audio_np.ndim > 1:
|
||||
audio_np = audio_np[:, 0]
|
||||
audio_output = (int(sample_rate), audio_np.astype(np.float32))
|
||||
for choice in chat_completion.choices:
|
||||
if choice.message.content:
|
||||
text_outputs.append(choice.message.content)
|
||||
if choice.message.audio:
|
||||
# Decode base64 audio
|
||||
audio_data = base64.b64decode(choice.message.audio.data)
|
||||
# Load audio from bytes
|
||||
audio_np, sample_rate = sf.read(io.BytesIO(audio_data))
|
||||
# Convert to mono if needed
|
||||
if audio_np.ndim > 1:
|
||||
audio_np = audio_np[:, 0]
|
||||
audio_output = (int(sample_rate), audio_np.astype(np.float32))
|
||||
|
||||
text_response = "\n\n".join(text_outputs) if text_outputs else "No text output."
|
||||
yield text_response, audio_output
|
||||
else:
|
||||
# Streaming mode: yield incremental updates
|
||||
text_content = ""
|
||||
audio_output = None
|
||||
|
||||
for chunk in chat_completion:
|
||||
for choice in chunk.choices:
|
||||
if hasattr(choice, "delta"):
|
||||
content = getattr(choice.delta, "content", None)
|
||||
else:
|
||||
content = None
|
||||
|
||||
# Handle audio modality
|
||||
if getattr(chunk, "modality", None) == "audio" and content:
|
||||
try:
|
||||
# Decode base64 audio
|
||||
audio_data = base64.b64decode(content)
|
||||
# Load audio from bytes
|
||||
audio_np, sample_rate = sf.read(io.BytesIO(audio_data))
|
||||
# Convert to mono if needed
|
||||
if audio_np.ndim > 1:
|
||||
audio_np = audio_np[:, 0]
|
||||
audio_output = (int(sample_rate), audio_np.astype(np.float32))
|
||||
# Yield current text and audio
|
||||
yield text_content if text_content else "", audio_output
|
||||
except Exception: # pylint: disable=broad-except
|
||||
# If audio processing fails, just yield text
|
||||
yield text_content if text_content else "", None
|
||||
|
||||
# Handle text modality
|
||||
elif getattr(chunk, "modality", None) == "text":
|
||||
if content:
|
||||
text_content += content
|
||||
# Yield updated text content (keep existing audio if any)
|
||||
yield text_content, audio_output
|
||||
|
||||
# Final yield with accumulated text and last audio (if any)
|
||||
yield text_content if text_content else "No text output.", audio_output
|
||||
|
||||
text_response = "\n\n".join(text_outputs) if text_outputs else "No text output."
|
||||
return text_response, audio_output
|
||||
except Exception as exc: # pylint: disable=broad-except
|
||||
return f"Inference failed: {exc}", None
|
||||
error_msg = f"Inference failed: {exc}"
|
||||
yield error_msg, None
|
||||
|
||||
|
||||
def build_interface(
|
||||
@@ -377,8 +420,10 @@ def build_interface(
|
||||
video_file: str | None,
|
||||
use_audio_in_video: bool,
|
||||
output_modalities: str | None = None,
|
||||
stream: bool = False,
|
||||
):
|
||||
return run_inference_api(
|
||||
# Always yield from the API function to maintain consistent generator behavior
|
||||
yield from run_inference_api(
|
||||
client,
|
||||
model,
|
||||
sampling_params_dict,
|
||||
@@ -388,6 +433,7 @@ def build_interface(
|
||||
video_file,
|
||||
use_audio_in_video,
|
||||
output_modalities,
|
||||
stream,
|
||||
)
|
||||
|
||||
css = """
|
||||
@@ -458,8 +504,15 @@ def build_interface(
|
||||
with gr.Row():
|
||||
output_modalities = gr.Textbox(
|
||||
label="Output Modalities",
|
||||
value=None,
|
||||
placeholder="For example: text, image, video. Use comma to separate multiple modalities.",
|
||||
lines=1,
|
||||
scale=2,
|
||||
)
|
||||
stream_checkbox = gr.Checkbox(
|
||||
label="Stream output",
|
||||
value=False,
|
||||
info="Enable streaming to see output as it's generated.",
|
||||
scale=1,
|
||||
)
|
||||
|
||||
@@ -477,7 +530,15 @@ def build_interface(
|
||||
|
||||
generate_btn.click(
|
||||
fn=run_inference,
|
||||
inputs=[input_box, audio_input, image_input, video_input, use_audio_in_video_checkbox, output_modalities],
|
||||
inputs=[
|
||||
input_box,
|
||||
audio_input,
|
||||
image_input,
|
||||
video_input,
|
||||
use_audio_in_video_checkbox,
|
||||
output_modalities,
|
||||
stream_checkbox,
|
||||
],
|
||||
outputs=[text_output, audio_output],
|
||||
)
|
||||
demo.queue()
|
||||
|
||||
+39
-10
@@ -395,19 +395,43 @@ def run_multimodal_generation(args) -> None:
|
||||
model=model_name,
|
||||
modalities=output_modalities,
|
||||
extra_body=extra_body,
|
||||
stream=args.stream,
|
||||
)
|
||||
|
||||
count = 0
|
||||
for choice in chat_completion.choices:
|
||||
if choice.message.audio:
|
||||
audio_data = base64.b64decode(choice.message.audio.data)
|
||||
audio_file_path = f"audio_{count}.wav"
|
||||
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)
|
||||
if not args.stream:
|
||||
for choice in chat_completion.choices:
|
||||
if choice.message.audio:
|
||||
audio_data = base64.b64decode(choice.message.audio.data)
|
||||
audio_file_path = f"audio_{count}.wav"
|
||||
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 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)
|
||||
audio_file_path = f"audio_{count}.wav"
|
||||
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():
|
||||
@@ -461,6 +485,11 @@ def parse_args():
|
||||
default=None,
|
||||
help="Output modalities to use for the prompts.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--stream",
|
||||
action="store_true",
|
||||
help="Stream the response.",
|
||||
)
|
||||
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
Reference in new issue
Block a user