[New Model]: Add sensenova u1 support (#3319)
Signed-off-by: princepride <wangzhipeng628@gmail.com> Signed-off-by: 汪志鹏 <wangzhipeng628@gmail.com>
This commit is contained in:
20 files changed
+3838
-19
No files matched your search
@@ -0,0 +1,208 @@
|
||||
# SenseNova-U1-8B-MoT
|
||||
|
||||
## Architecture
|
||||
|
||||
SenseNova-U1 is a unified Qwen3-based LLM with Mixture-of-Tokenizers (MoT) attention. Unlike two-stage pipelines (e.g., BAGEL), it handles text encoding, optional reasoning ("think mode"), and flow-matching-based image denoising entirely within a single diffusion stage.
|
||||
|
||||
| Feature | Description |
|
||||
| :------ | :---------- |
|
||||
| **Model type** | Unified LLM (single-stage diffusion pipeline) |
|
||||
| **Base LLM** | Qwen3 with MoT attention and 3D RoPE |
|
||||
| **Image generation** | Flow-matching Euler sampler, no separate VAE |
|
||||
| **Think mode** | Optional chain-of-thought reasoning before image generation |
|
||||
| **Parallelism** | Tensor Parallelism (TP) with fused QKV and fused gate/up projections |
|
||||
| **Modalities** | text2img, img2img, img2text (understanding), text2text |
|
||||
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
cd examples/offline_inference/sensenova_u1
|
||||
|
||||
# Text-to-image
|
||||
python end2end.py --prompt "A cute cat" --think
|
||||
|
||||
# Image-to-image editing
|
||||
python end2end.py --prompt "Turn this into an oil painting" \
|
||||
--image input.png --think
|
||||
|
||||
# Image understanding (img2text)
|
||||
python end2end.py --modality img2text \
|
||||
--prompt "Describe this image in detail" \
|
||||
--image photo.jpg
|
||||
|
||||
# Text-to-text (pure chat)
|
||||
python end2end.py --modality text2text \
|
||||
--prompt "What is the capital of France?"
|
||||
|
||||
# Custom resolution (image generation)
|
||||
python end2end.py --prompt "A futuristic cityscape at sunset" \
|
||||
--width 2048 --height 1024 --think
|
||||
```
|
||||
|
||||
> **Note**: Default configuration works on a single **NVIDIA A100 (80GB)** or **H100** GPU.
|
||||
|
||||
## Text-to-Image (t2i)
|
||||
|
||||
Standard text-to-image with optional think mode:
|
||||
|
||||
```bash
|
||||
python end2end.py \
|
||||
--prompt "Close portrait of an elderly woman by a farmhouse window, textured skin, gentle smile, warm natural light" \
|
||||
--width 1536 --height 2720 \
|
||||
--think --print-think
|
||||
```
|
||||
|
||||
## Image-to-Image Editing (img2img)
|
||||
|
||||
Pass one or more `--image` paths to trigger img2img mode. The model uses the
|
||||
input image(s) as visual context for editing:
|
||||
|
||||
```bash
|
||||
# Single input image
|
||||
python end2end.py \
|
||||
--prompt "Add a sunset sky in the background" \
|
||||
--image photo.jpg \
|
||||
--width 2048 --height 2048 \
|
||||
--think
|
||||
|
||||
# Multiple reference images
|
||||
python end2end.py \
|
||||
--prompt "Combine the style of Image-1 with the content of Image-2" \
|
||||
--image style_ref.png content_ref.png \
|
||||
--width 2048 --height 2048 \
|
||||
--think
|
||||
```
|
||||
|
||||
### Dual CFG for img2img
|
||||
|
||||
img2img supports dual classifier-free guidance (text CFG + image CFG):
|
||||
|
||||
```bash
|
||||
python end2end.py \
|
||||
--prompt "Make the person smile" \
|
||||
--image portrait.jpg \
|
||||
--cfg-scale 4.0 \
|
||||
--img-cfg-scale 2.0 \
|
||||
--think
|
||||
```
|
||||
|
||||
| `img_cfg_scale` | Behavior |
|
||||
| :-------------- | :------- |
|
||||
| `1.0` (default) | Text-only CFG: guidance = image-condition → full-condition |
|
||||
| `== cfg_scale` | Standard CFG: guidance = unconditional → full-condition |
|
||||
| Other value | Dual CFG: separate text and image guidance strengths |
|
||||
|
||||
## Full Parameter Reference
|
||||
|
||||
### General Parameters
|
||||
|
||||
| Parameter | Default | Description |
|
||||
| :-------- | :------ | :---------- |
|
||||
| `--modality` | `auto` | Task modality: `auto`, `text2img`, `img2img`, `img2text`, `text2text` |
|
||||
| `--prompt` | "A cute cat..." | Text prompt / editing instruction / question |
|
||||
| `--image` | None | Input image path(s) for img2img or img2text |
|
||||
|
||||
### Image Generation Parameters (text2img / img2img)
|
||||
|
||||
| Parameter | Default | Description |
|
||||
| :-------- | :------ | :---------- |
|
||||
| `--height` | 2048 | Height of generated image (pixels) |
|
||||
| `--width` | 2048 | Width of generated image (pixels) |
|
||||
| `--seed` | 42 | Random seed for reproducibility |
|
||||
| `--num-steps` | 50 | Number of denoising steps |
|
||||
| `--cfg-scale` | 4.0 | Text classifier-free guidance scale |
|
||||
| `--img-cfg-scale` | 1.0 | Image CFG scale (img2img only, 1.0 = disabled) |
|
||||
| `--cfg-norm` | "none" | CFG normalization: none, global, channel, cfg_zero_star (t2i only) |
|
||||
| `--timestep-shift` | 3.0 | Timestep shift for flow-matching schedule |
|
||||
| `--t-eps` | 0.02 | Epsilon for timestep schedule |
|
||||
| `--think` | False | Enable think mode |
|
||||
| `--print-think` | False | Print think text to stdout |
|
||||
|
||||
### Text Generation Parameters (text2text / img2text)
|
||||
|
||||
| Parameter | Default | Description |
|
||||
| :-------- | :------ | :---------- |
|
||||
| `--max-tokens` | 512 | Maximum number of tokens to generate |
|
||||
| `--do-sample` | False | Use sampling instead of greedy decoding |
|
||||
| `--temperature` | 0.7 | Sampling temperature (higher = more diverse) |
|
||||
|
||||
### Infrastructure Parameters
|
||||
|
||||
| Parameter | Default | Description |
|
||||
| :-------- | :------ | :---------- |
|
||||
| `--model` | `SenseNova/SenseNova-U1-8B-MoT` | HuggingFace model ID or local path |
|
||||
| `--output` | `.` | Output directory for saved images |
|
||||
| `--tensor-parallel-size` | 1 | Number of GPUs for tensor parallelism |
|
||||
| `--enforce-eager` | False | Disable torch.compile |
|
||||
| `--enable-cpu-offload` | False | Enable module-wise (sequential) CPU offload to reduce peak VRAM |
|
||||
|
||||
## Reducing GPU Memory Usage
|
||||
|
||||
For hardware with limited VRAM, enable **module-wise CPU offload** with
|
||||
`--enable-cpu-offload`. The pipeline implements `SupportsModuleOffload`, so the
|
||||
vision encoder (`vision_model`) and the Qwen3 LLM (`language_model`) are
|
||||
swapped between CPU and GPU on demand:
|
||||
|
||||
- During text/vision encoding, the LLM is on CPU.
|
||||
- During the diffusion loop, the vision encoder is on CPU.
|
||||
- Lightweight FM modules stay resident on GPU.
|
||||
|
||||
This lowers peak VRAM at the cost of extra CPU<->GPU transfers (use pinned
|
||||
memory) — useful for running SenseNova-U1 on consumer-grade GPUs.
|
||||
|
||||
```bash
|
||||
# Text-to-image with CPU offload
|
||||
python end2end.py \
|
||||
--prompt "A cute cat sitting on a windowsill" \
|
||||
--width 2048 --height 2048 \
|
||||
--enable-cpu-offload --think
|
||||
|
||||
# Image-to-image editing with CPU offload
|
||||
python end2end.py \
|
||||
--prompt "Turn this into an oil painting" \
|
||||
--image input.png \
|
||||
--width 2048 --height 2048 \
|
||||
--enable-cpu-offload --think
|
||||
|
||||
# Image understanding (img2text) with CPU offload
|
||||
python end2end.py \
|
||||
--modality img2text \
|
||||
--prompt "Describe this image in detail" \
|
||||
--image photo.jpg \
|
||||
--enable-cpu-offload
|
||||
```
|
||||
|
||||
> **Notes**
|
||||
> - CPU offload is **single-GPU only** (incompatible with `--tensor-parallel-size > 1`).
|
||||
> - First-step latency is higher because of the cold-start CPU<->GPU transfers.
|
||||
> - For more details and other offloading strategies, see
|
||||
> [CPU Offloading for Diffusion Models](../../../docs/user_guide/diffusion/cpu_offload_diffusion.md).
|
||||
|
||||
## Reproducing the E2E Test
|
||||
|
||||
The following command reproduces the pixel-validated CI test case:
|
||||
|
||||
```bash
|
||||
python end2end.py \
|
||||
--prompt "Close portrait of an elderly woman by a farmhouse window, textured skin, gentle smile, warm natural light, emotional documentary look. The portrait should feel polished and natural, with sharp eyes, realistic skin texture, accurate facial anatomy, and premium lighting that keeps the face as the main focus." \
|
||||
--width 1536 --height 2720 \
|
||||
--seed 42 --num-steps 50 \
|
||||
--cfg-scale 4.0 --timestep-shift 3.0 --cfg-norm none \
|
||||
--think --print-think \
|
||||
--output outputs
|
||||
```
|
||||
|
||||
The corresponding pytest:
|
||||
|
||||
```bash
|
||||
pytest -s -v tests/e2e/offline_inference/test_sensenova_u1_text2img.py \
|
||||
-m "advanced_model" --run-level "advanced_model"
|
||||
```
|
||||
|
||||
The img2img counterpart lives at
|
||||
`tests/e2e/offline_inference/test_sensenova_u1_img2img.py`.
|
||||
|
||||
## Online Serving
|
||||
|
||||
For OpenAI-compatible API serving, see
|
||||
[`examples/online_serving/sensenova_u1/`](../../examples/online_serving/sensenova_u1/).
|
||||
@@ -0,0 +1,281 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
"""
|
||||
End-to-end offline inference for SenseNova-U1-8B-MoT.
|
||||
|
||||
Supports four modalities: text2img, img2img, img2text, text2text.
|
||||
|
||||
Text-to-image:
|
||||
python end2end.py --prompt "A cute cat" --think
|
||||
|
||||
Image-to-image (editing):
|
||||
python end2end.py --prompt "Turn this into an oil painting" \
|
||||
--image input.png --think
|
||||
|
||||
Image understanding:
|
||||
python end2end.py --modality img2text \
|
||||
--prompt "Describe this image" --image photo.jpg
|
||||
|
||||
Text chat:
|
||||
python end2end.py --modality text2text \
|
||||
--prompt "What is the capital of France?"
|
||||
|
||||
See README.md for more examples.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from vllm_omni.engine.arg_utils import nullify_stage_engine_defaults
|
||||
from vllm_omni.entrypoints.omni import Omni
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams
|
||||
|
||||
|
||||
def parse_args():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="SenseNova-U1 text-to-image / image-to-image / text / understanding via vLLM-Omni.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--model",
|
||||
default="SenseNova/SenseNova-U1-8B-MoT",
|
||||
help="HuggingFace model ID or local path.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--modality",
|
||||
default="auto",
|
||||
choices=["auto", "text2img", "img2img", "img2text", "text2text"],
|
||||
help="Task modality. 'auto' infers from --image (img2img/img2text if images, else t2i/t2t).",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--prompt",
|
||||
default="A cute cat sitting on a windowsill, soft natural light",
|
||||
help="Text prompt for generation or editing instruction.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--image",
|
||||
nargs="+",
|
||||
metavar="PATH",
|
||||
default=None,
|
||||
help="Input image path(s) for img2img or img2text.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--output",
|
||||
type=str,
|
||||
default=".",
|
||||
help="Output directory to save generated images.",
|
||||
)
|
||||
# Image dimensions
|
||||
parser.add_argument("--height", type=int, default=2048, help="Height of generated image.")
|
||||
parser.add_argument("--width", type=int, default=2048, help="Width of generated image.")
|
||||
|
||||
# Generation parameters
|
||||
parser.add_argument("--seed", type=int, default=42, help="Random seed for deterministic results.")
|
||||
parser.add_argument("--num-steps", type=int, default=50, help="Number of denoising steps.")
|
||||
parser.add_argument("--cfg-scale", type=float, default=4.0, help="Text classifier-free guidance scale.")
|
||||
parser.add_argument(
|
||||
"--img-cfg-scale",
|
||||
type=float,
|
||||
default=1.0,
|
||||
help="Image CFG scale for img2img (1.0 = disabled). "
|
||||
"When both --cfg-scale and --img-cfg-scale differ, dual CFG is used.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--cfg-norm",
|
||||
type=str,
|
||||
default="none",
|
||||
choices=["none", "global", "channel", "cfg_zero_star"],
|
||||
help="CFG normalization mode. cfg_zero_star is only for t2i.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--timestep-shift",
|
||||
type=float,
|
||||
default=3.0,
|
||||
help="Timestep shift for flow-matching schedule.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--t-eps",
|
||||
type=float,
|
||||
default=0.02,
|
||||
help="Epsilon for flow-matching timestep schedule.",
|
||||
)
|
||||
|
||||
# Text generation parameters (for text2text / img2text)
|
||||
parser.add_argument(
|
||||
"--max-tokens",
|
||||
type=int,
|
||||
default=2048,
|
||||
help="Max tokens for text generation (text2text / img2text).",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--do-sample",
|
||||
action="store_true",
|
||||
help="Use sampling instead of greedy decoding for text generation.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--temperature",
|
||||
type=float,
|
||||
default=0.7,
|
||||
help="Sampling temperature for text generation.",
|
||||
)
|
||||
|
||||
# Think mode
|
||||
parser.add_argument(
|
||||
"--think",
|
||||
action="store_true",
|
||||
help="Enable think mode: the model reasons about the prompt before generating the image.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--print-think",
|
||||
action="store_true",
|
||||
help="Print the generated think text to stdout.",
|
||||
)
|
||||
|
||||
# Advanced
|
||||
parser.add_argument(
|
||||
"--tensor-parallel-size",
|
||||
type=int,
|
||||
default=1,
|
||||
help="Number of GPUs for tensor parallelism.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--enforce-eager",
|
||||
action="store_true",
|
||||
help="Disable torch.compile and force eager execution.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--enable-cpu-offload",
|
||||
action="store_true",
|
||||
help=(
|
||||
"Enable model-level (sequential) CPU offloading. "
|
||||
"Mutually exclusive between vision_model and language_model: "
|
||||
"only one is on GPU at a time, reducing peak VRAM at the cost "
|
||||
"of extra CPU<->GPU transfers."
|
||||
),
|
||||
)
|
||||
|
||||
nullify_stage_engine_defaults(parser)
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def _resolve_modality(args):
|
||||
"""Determine the effective modality from CLI args."""
|
||||
if args.modality != "auto":
|
||||
return args.modality
|
||||
has_images = args.image is not None
|
||||
# Default: image-producing tasks for backward compatibility
|
||||
return "img2img" if has_images else "text2img"
|
||||
|
||||
|
||||
def main():
|
||||
args = parse_args()
|
||||
os.makedirs(args.output, exist_ok=True)
|
||||
|
||||
modality = _resolve_modality(args)
|
||||
is_text_output = modality in ("text2text", "img2text")
|
||||
has_images = modality in ("img2img", "img2text")
|
||||
|
||||
omni = Omni(
|
||||
model=args.model,
|
||||
tensor_parallel_size=args.tensor_parallel_size,
|
||||
enforce_eager=args.enforce_eager,
|
||||
enable_cpu_offload=args.enable_cpu_offload,
|
||||
)
|
||||
|
||||
extra_args = {
|
||||
"cfg_scale": args.cfg_scale,
|
||||
"cfg_norm": args.cfg_norm,
|
||||
"timestep_shift": args.timestep_shift,
|
||||
"cfg_interval": (0.0, 1.0),
|
||||
"batch_size": 1,
|
||||
"think": args.think,
|
||||
"t_eps": args.t_eps,
|
||||
}
|
||||
if modality == "img2img":
|
||||
extra_args["img_cfg_scale"] = args.img_cfg_scale
|
||||
if is_text_output:
|
||||
extra_args["max_tokens"] = args.max_tokens
|
||||
extra_args["do_sample"] = args.do_sample
|
||||
extra_args["temperature"] = args.temperature
|
||||
|
||||
sampling_params = OmniDiffusionSamplingParams(
|
||||
height=args.height,
|
||||
width=args.width,
|
||||
seed=args.seed,
|
||||
num_inference_steps=args.num_steps,
|
||||
extra_args=extra_args,
|
||||
)
|
||||
|
||||
print(f"\n{'=' * 60}")
|
||||
print(f"SenseNova-U1 Configuration ({modality}):")
|
||||
print(f" Model : {args.model}")
|
||||
if not is_text_output:
|
||||
print(f" Image size : {args.width}x{args.height}")
|
||||
print(f" Steps : {args.num_steps}")
|
||||
print(f" CFG scale : {args.cfg_scale}")
|
||||
if modality == "img2img":
|
||||
print(f" Img CFG scale : {args.img_cfg_scale}")
|
||||
if has_images:
|
||||
print(f" Input images : {args.image}")
|
||||
if is_text_output:
|
||||
print(f" Max tokens : {args.max_tokens}")
|
||||
print(f" Temperature : {args.temperature}")
|
||||
print(f" Seed : {args.seed}")
|
||||
print(f" Think mode : {args.think}")
|
||||
print(f" TP size : {args.tensor_parallel_size}")
|
||||
print(f"{'=' * 60}\n")
|
||||
|
||||
# Build prompt dict
|
||||
if has_images:
|
||||
if not args.image:
|
||||
raise ValueError(f"{modality} requires --image.")
|
||||
input_images = [Image.open(p).convert("RGB") for p in args.image]
|
||||
if is_text_output:
|
||||
prompt_dict = {
|
||||
"prompt": args.prompt,
|
||||
"multi_modal_data": {"image": input_images},
|
||||
"modalities": ["text"],
|
||||
}
|
||||
else:
|
||||
prompt_dict = {
|
||||
"prompt": args.prompt,
|
||||
"multi_modal_data": {"image": input_images},
|
||||
"modalities": ["img2img"],
|
||||
}
|
||||
elif is_text_output:
|
||||
prompt_dict = {"prompt": args.prompt, "modalities": ["text"]}
|
||||
else:
|
||||
prompt_dict = {"prompt": args.prompt, "modalities": ["image"]}
|
||||
|
||||
outputs = list(
|
||||
omni.generate(
|
||||
prompts=prompt_dict,
|
||||
sampling_params_list=sampling_params,
|
||||
)
|
||||
)
|
||||
|
||||
for req_output in outputs:
|
||||
custom = getattr(req_output, "_custom_output", {}) or {}
|
||||
if args.print_think and custom.get("think_text"):
|
||||
print(f"[Think]\n{custom['think_text']}\n")
|
||||
|
||||
if is_text_output:
|
||||
text = custom.get("text_output", "")
|
||||
if not text:
|
||||
text = getattr(req_output, "text", "") or ""
|
||||
print(f"[Response]\n{text}")
|
||||
else:
|
||||
images = getattr(req_output, "images", None) or []
|
||||
if not images:
|
||||
print("[Warning] No images generated.")
|
||||
continue
|
||||
for j, img in enumerate(images):
|
||||
save_path = os.path.join(args.output, f"sensenova_u1_output_{j}.png")
|
||||
img.save(save_path)
|
||||
print(f"[Output] Saved {img.size[0]}x{img.size[1]} image to {save_path}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,163 @@
|
||||
# SenseNova-U1 Online Serving
|
||||
|
||||
## Launch the Server
|
||||
|
||||
```bash
|
||||
vllm serve SenseNova/SenseNova-U1-8B-MoT --omni --port 8091
|
||||
```
|
||||
|
||||
Or use the convenience script:
|
||||
|
||||
```bash
|
||||
cd examples/online_serving/sensenova_u1
|
||||
bash run_server.sh
|
||||
```
|
||||
|
||||
### Tensor Parallelism (TP)
|
||||
|
||||
```bash
|
||||
vllm serve SenseNova/SenseNova-U1-8B-MoT --omni --port 8091 \
|
||||
--tensor-parallel-size 2
|
||||
```
|
||||
|
||||
## Send Requests
|
||||
|
||||
```bash
|
||||
cd examples/online_serving/sensenova_u1
|
||||
```
|
||||
|
||||
### Text to Image (text2img)
|
||||
|
||||
**Python client:**
|
||||
|
||||
```bash
|
||||
python openai_chat_client.py \
|
||||
--prompt "A beautiful sunset over mountains" \
|
||||
--modality text2img \
|
||||
--height 2048 --width 2048 --num-steps 50
|
||||
```
|
||||
|
||||
**curl:**
|
||||
|
||||
```bash
|
||||
curl http://localhost:8091/v1/chat/completions \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"messages": [{"role": "user", "content": [{"type": "text", "text": "A beautiful sunset over mountains"}]}],
|
||||
"modalities": ["image"],
|
||||
"height": 2048,
|
||||
"width": 2048,
|
||||
"num_inference_steps": 50,
|
||||
"seed": 42
|
||||
}'
|
||||
```
|
||||
|
||||
### Image to Image (img2img)
|
||||
|
||||
**Python client:**
|
||||
|
||||
```bash
|
||||
python openai_chat_client.py \
|
||||
--prompt "Turn this into an oil painting" \
|
||||
--modality img2img \
|
||||
--image-url /path/to/input.jpg \
|
||||
--height 2048 --width 2048
|
||||
```
|
||||
|
||||
**curl:**
|
||||
|
||||
```bash
|
||||
IMAGE_BASE64=$(base64 -w 0 input.jpg)
|
||||
|
||||
cat <<EOF > payload.json
|
||||
{
|
||||
"messages": [{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{"type": "text", "text": "Turn this into an oil painting"},
|
||||
{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64,${IMAGE_BASE64}"}}
|
||||
]
|
||||
}],
|
||||
"modalities": ["image"],
|
||||
"height": 2048,
|
||||
"width": 2048,
|
||||
"num_inference_steps": 50,
|
||||
"seed": 42
|
||||
}
|
||||
EOF
|
||||
|
||||
curl http://localhost:8091/v1/chat/completions \
|
||||
-H "Content-Type: application/json" \
|
||||
-d @payload.json
|
||||
```
|
||||
|
||||
### Image to Text (img2text)
|
||||
|
||||
**Python client:**
|
||||
|
||||
```bash
|
||||
python openai_chat_client.py \
|
||||
--prompt "Describe this image in detail" \
|
||||
--modality img2text \
|
||||
--image-url /path/to/image.jpg
|
||||
```
|
||||
|
||||
**curl:**
|
||||
|
||||
```bash
|
||||
IMAGE_BASE64=$(base64 -w 0 image.jpg)
|
||||
|
||||
cat <<EOF > payload.json
|
||||
{
|
||||
"messages": [{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{"type": "text", "text": "Describe this image in detail"},
|
||||
{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64,${IMAGE_BASE64}"}}
|
||||
]
|
||||
}],
|
||||
"modalities": ["text"]
|
||||
}
|
||||
EOF
|
||||
|
||||
curl http://localhost:8091/v1/chat/completions \
|
||||
-H "Content-Type: application/json" \
|
||||
-d @payload.json
|
||||
```
|
||||
|
||||
### Text to Text (text2text)
|
||||
|
||||
**Python client:**
|
||||
|
||||
```bash
|
||||
python openai_chat_client.py \
|
||||
--prompt "What is the capital of France?" \
|
||||
--modality text2text
|
||||
```
|
||||
|
||||
**curl:**
|
||||
|
||||
```bash
|
||||
curl http://localhost:8091/v1/chat/completions \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"messages": [{"role": "user", "content": [{"type": "text", "text": "What is the capital of France?"}]}],
|
||||
"modalities": ["text"]
|
||||
}'
|
||||
```
|
||||
|
||||
## Python Client Arguments
|
||||
|
||||
| Argument | Default | Description |
|
||||
| :------- | :------ | :---------- |
|
||||
| `--prompt` / `-p` | `A cute cat` | Text prompt |
|
||||
| `--output` / `-o` | `sensenova_u1_output.png` | Output file path |
|
||||
| `--server` / `-s` | `http://localhost:8091` | Server URL |
|
||||
| `--image-url` / `-i` | `None` | Input image URL or local path (img2img/img2text) |
|
||||
| `--modality` / `-m` | `text2img` | `text2img`, `img2img`, `img2text`, `text2text` |
|
||||
| `--height` | `2048` | Image height (image generation only) |
|
||||
| `--width` | `2048` | Image width (image generation only) |
|
||||
| `--num-steps` | `50` | Number of inference steps (image generation only) |
|
||||
| `--seed` | `42` | Random seed |
|
||||
| `--cfg-scale` | `4.0` | CFG scale (image generation only) |
|
||||
| `--think` | `False` | Enable think mode |
|
||||
@@ -0,0 +1,188 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
SenseNova-U1 OpenAI-compatible chat client for all four task modalities.
|
||||
|
||||
Usage:
|
||||
# Text-to-image
|
||||
python openai_chat_client.py --prompt "A cute cat" --modality text2img
|
||||
|
||||
# Image-to-image editing
|
||||
python openai_chat_client.py --prompt "Turn this into an oil painting" \
|
||||
--modality img2img --image-url /path/to/image.jpg
|
||||
|
||||
# Image understanding (img2text)
|
||||
python openai_chat_client.py --prompt "Describe this image in detail" \
|
||||
--modality img2text --image-url /path/to/image.jpg
|
||||
|
||||
# Text-to-text (chat)
|
||||
python openai_chat_client.py --prompt "What is the capital of France?" \
|
||||
--modality text2text
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
from pathlib import Path
|
||||
|
||||
import requests
|
||||
|
||||
|
||||
def _encode_image(image_url: str) -> str:
|
||||
"""Encode a local file or URL to a base64 data URI."""
|
||||
if Path(image_url).exists():
|
||||
with open(image_url, "rb") as f:
|
||||
b64_data = base64.b64encode(f.read()).decode("utf-8")
|
||||
return f"data:image/jpeg;base64,{b64_data}"
|
||||
return image_url
|
||||
|
||||
|
||||
def generate(
|
||||
prompt: str,
|
||||
server_url: str = "http://localhost:8091",
|
||||
image_url: str | None = None,
|
||||
modality: str = "text2img",
|
||||
**kwargs: object,
|
||||
) -> bytes | str | None:
|
||||
"""Send a request to the SenseNova-U1 server.
|
||||
|
||||
All keyword arguments (height, width, seed, cfg_scale, think, …) are
|
||||
forwarded as top-level fields in the request payload. The serving layer
|
||||
maps standard keys (height, width, seed, num_inference_steps) to sampling
|
||||
params and forwards model-specific keys (think, cfg_norm, img_cfg_scale,
|
||||
…) to ``extra_args`` based on the pipeline's ``EXTRA_BODY_PARAMS``.
|
||||
|
||||
Returns:
|
||||
Image bytes (for image outputs) or text string (for text outputs).
|
||||
"""
|
||||
content = [{"type": "text", "text": prompt}]
|
||||
|
||||
if image_url:
|
||||
content.append({"type": "image_url", "image_url": {"url": _encode_image(image_url)}})
|
||||
|
||||
messages = [{"role": "user", "content": content}]
|
||||
payload: dict = {"messages": messages}
|
||||
|
||||
if modality in ("text2img", "img2img"):
|
||||
payload["modalities"] = ["image"]
|
||||
else:
|
||||
payload["modalities"] = ["text"]
|
||||
|
||||
for key, val in kwargs.items():
|
||||
if val is not None and val is not False:
|
||||
payload[key] = val
|
||||
|
||||
try:
|
||||
print(f"Sending {modality} request to {server_url}...")
|
||||
response = requests.post(
|
||||
f"{server_url}/v1/chat/completions",
|
||||
headers={"Content-Type": "application/json"},
|
||||
json=payload,
|
||||
timeout=600,
|
||||
)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
|
||||
# Print think text if present in response metrics
|
||||
metrics = data.get("metrics") or {}
|
||||
think_text = metrics.get("think_text")
|
||||
if think_text:
|
||||
print(f"\n[Think]\n{think_text}\n")
|
||||
|
||||
choices = data.get("choices", [])
|
||||
|
||||
for choice in choices:
|
||||
choice_content = choice.get("message", {}).get("content")
|
||||
|
||||
if isinstance(choice_content, list) and len(choice_content) > 0:
|
||||
first_item = choice_content[0]
|
||||
if isinstance(first_item, dict) and "image_url" in first_item:
|
||||
img_url_str = first_item["image_url"].get("url", "")
|
||||
if img_url_str.startswith("data:image"):
|
||||
_, b64_data = img_url_str.split(",", 1)
|
||||
return base64.b64decode(b64_data)
|
||||
|
||||
for choice in choices:
|
||||
choice_content = choice.get("message", {}).get("content")
|
||||
if isinstance(choice_content, str) and choice_content:
|
||||
return choice_content
|
||||
|
||||
print(f"Unexpected response format: {choices}")
|
||||
return None
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error: {e}")
|
||||
return None
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="SenseNova-U1 multimodal chat client")
|
||||
parser.add_argument("--prompt", "-p", default="A cute cat", help="Text prompt")
|
||||
parser.add_argument("--output", "-o", default="sensenova_u1_output.png", help="Output file (for image results)")
|
||||
parser.add_argument("--server", "-s", default="http://localhost:8091", help="Server URL")
|
||||
parser.add_argument("--image-url", "-i", type=str, help="Input image URL or local path")
|
||||
parser.add_argument(
|
||||
"--modality",
|
||||
"-m",
|
||||
default="text2img",
|
||||
choices=["text2img", "img2img", "img2text", "text2text"],
|
||||
help="Task modality",
|
||||
)
|
||||
# Standard generation parameters
|
||||
parser.add_argument("--height", type=int, default=2048, help="Image height")
|
||||
parser.add_argument("--width", type=int, default=2048, help="Image width")
|
||||
parser.add_argument("--num-steps", type=int, default=50, help="Inference steps")
|
||||
parser.add_argument("--seed", type=int, default=42, help="Random seed")
|
||||
# Model-specific parameters (forwarded via EXTRA_BODY_PARAMS)
|
||||
parser.add_argument("--cfg-scale", type=float, default=4.0, help="CFG scale")
|
||||
parser.add_argument("--img-cfg-scale", type=float, help="Image CFG scale (img2img)")
|
||||
parser.add_argument("--cfg-norm", type=str, help="CFG normalization mode")
|
||||
parser.add_argument("--timestep-shift", type=float, help="Timestep shift")
|
||||
parser.add_argument("--think", action="store_true", help="Enable think mode")
|
||||
|
||||
args = parser.parse_args()
|
||||
is_image = args.modality in ("text2img", "img2img")
|
||||
|
||||
print(f"Mode: {args.modality}")
|
||||
if args.image_url:
|
||||
print(f"Input Image: {args.image_url}")
|
||||
|
||||
extra: dict[str, object] = {
|
||||
"seed": args.seed,
|
||||
"think": args.think or None,
|
||||
}
|
||||
if is_image:
|
||||
extra.update(
|
||||
height=args.height,
|
||||
width=args.width,
|
||||
num_inference_steps=args.num_steps,
|
||||
cfg_scale=args.cfg_scale,
|
||||
)
|
||||
if args.img_cfg_scale is not None:
|
||||
extra["img_cfg_scale"] = args.img_cfg_scale
|
||||
if args.cfg_norm is not None:
|
||||
extra["cfg_norm"] = args.cfg_norm
|
||||
if args.timestep_shift is not None:
|
||||
extra["timestep_shift"] = args.timestep_shift
|
||||
|
||||
result = generate(
|
||||
prompt=args.prompt,
|
||||
server_url=args.server,
|
||||
image_url=args.image_url,
|
||||
modality=args.modality,
|
||||
**extra,
|
||||
)
|
||||
|
||||
if result:
|
||||
if isinstance(result, bytes):
|
||||
output_path = Path(args.output)
|
||||
output_path.write_bytes(result)
|
||||
print(f"Image saved to: {output_path}")
|
||||
print(f"Size: {len(result) / 1024:.1f} KB")
|
||||
elif isinstance(result, str):
|
||||
print(f"[Response]\n{result}")
|
||||
else:
|
||||
print("Failed to generate response")
|
||||
exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,12 @@
|
||||
#!/bin/bash
|
||||
# SenseNova-U1 online serving startup script
|
||||
|
||||
MODEL="${MODEL:-SenseNova/SenseNova-U1-8B-MoT}"
|
||||
PORT="${PORT:-8091}"
|
||||
|
||||
echo "Starting SenseNova-U1 server..."
|
||||
echo "Model: $MODEL"
|
||||
echo "Port: $PORT"
|
||||
|
||||
vllm serve "$MODEL" --omni \
|
||||
--port "$PORT"
|
||||
Reference in new issue
Block a user