Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions docs/api_usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -206,3 +206,46 @@ with Path("audio.wav").open("rb") as f:

print(response.text)
```

## Qwen4-MoE (images and video)

Models whose `config.json` has `"model_type": "qwen4_moe"` load as `model_type: vlm` with `engine: ovgenai`, as
usual, and run on `openvino_genai.Qwen4MoePipeline`. Every image and video is decoded and preprocessed in Python with
the model's own Hugging Face processors (`openvino_genai.qwen4_moe`), the same preprocessing the model was trained
with. The language model, scheduler config, draft model (MTP), `CACHE_DIR` and `runtime_config` are exactly what
`VLMPipeline` would use. Set `OPENARC_QWEN4_MOE_PIPELINE=0` to serve these models with `VLMPipeline` instead
(images only); an `openvino-genai` without `Qwen4MoePipeline` falls back to it automatically.

Next to `text`, a user message accepts these content items. Media must be base64 data URLs:

```python
import base64
import os
from openai import OpenAI

client = OpenAI(base_url="http://localhost:8000/v1", api_key=os.environ["OPENARC_API_KEY"])

def data_url(path, mime):
return f"data:{mime};base64," + base64.b64encode(open(path, "rb").read()).decode()

response = client.chat.completions.create(
model="<model-name>",
messages=[{
"role": "user",
"content": [
{"type": "image_url", "image_url": {"url": data_url("cat.png", "image/png")}},
# an encoded video, decoded with PyAV (pip install av) or OpenCV; "fps" optionally overrides the
# container's frame rate
{"type": "video_url", "video_url": {"url": data_url("clip.mp4", "video/mp4")}},
# or a video as already-decoded frames, with the rate they were taken at
{"type": "video", "video": [data_url(f"frame{i}.jpg", "image/jpeg") for i in range(8)], "fps": 2},
{"type": "text", "text": "What does the cat do in the clip?"},
],
}],
)
print(response.choices[0].message.content)
```

Frames are sampled and timestamped by the Qwen3-VL video processor (its defaults, or the model folder's
`video_preprocessor_config.json`). An image or video that cannot be decoded fails only that request with HTTP 400;
the model stays loaded.
275 changes: 275 additions & 0 deletions src/engine/ov_genai/qwen4_moe_vlm.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,275 @@
"""Qwen4-MoE (model_type qwen4_moe) on openvino_genai.Qwen4MoePipeline.

Same server contract as OVGenAI_VLM (OpenAI messages in, text, streaming, tool calls, metrics out) and the same
pipeline properties (scheduler config, draft model, CACHE_DIR, runtime_config), so the language model and its
graphs are exactly what VLMPipeline would run. The difference is the input side: every image and video is decoded
and preprocessed here in Python with the model's own Hugging Face processors (openvino_genai.qwen4_moe), and
Qwen4MoePipeline takes the resulting pixel_values. Videos are supported as well as images.

Accepted user content items, next to {"type": "text"}:
{"type": "image_url", "image_url": {"url": "data:image/...;base64,..."}}
{"type": "video_url", "video_url": {"url": "data:video/...;base64,...", "fps": 30}} (decoded with PyAV or OpenCV)
{"type": "video", "video": ["data:image/...;base64,...", ...], "fps": 2} (frames already decoded)
"fps" is the source frame rate and is optional; for an encoded video the container's rate is used.
"""

from __future__ import annotations

import base64
import json
import logging
import os
import tempfile
from dataclasses import dataclass, field
from io import BytesIO
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple

import numpy as np
import openvino_genai
from PIL import Image

from src.engine.ov_genai.vlm import OVGenAI_VLM
from src.engine.vision import VisionInputError
from src.server.schemas.modeling.contract_ovgenai_llm_and_vlm import OVGenAI_GenConfig
from src.server.utils.chat import flatten_message_content, flatten_messages

logger = logging.getLogger(__name__)

IMAGE_TAG = "<|vision_start|><|image_pad|><|vision_end|>"
VIDEO_TAG = "<|vision_start|><|video_pad|><|vision_end|>"

# Set to 0 to serve qwen4_moe models with the stock VLMPipeline (fused OpenVINO image preprocessing, images only).
QWEN4_MOE_PIPELINE_ENV = "OPENARC_QWEN4_MOE_PIPELINE"


def qwen4_moe_pipeline_available() -> bool:
return hasattr(openvino_genai, "Qwen4MoePipeline")


def is_qwen4_moe_model(model_path: str) -> bool:
"""True when config.json declares model_type qwen4_moe."""
try:
config = json.loads((Path(model_path) / "config.json").read_text(encoding="utf-8"))
except (OSError, ValueError):
return False
return isinstance(config, dict) and config.get("model_type") == "qwen4_moe"


def use_qwen4_moe_pipeline(model_path: str) -> bool:
"""Whether a VLM load should go to OVGenAI_Qwen4MoeVLM instead of OVGenAI_VLM."""
if not is_qwen4_moe_model(model_path):
return False
if os.getenv(QWEN4_MOE_PIPELINE_ENV, "1").strip().lower() in ("0", "false", "no", "off"):
logger.info(f"{QWEN4_MOE_PIPELINE_ENV} is off: serving {model_path} with VLMPipeline")
return False
if not qwen4_moe_pipeline_available():
logger.warning(
"openvino_genai has no Qwen4MoePipeline; serving the qwen4_moe model with VLMPipeline (images only). "
"Install an openvino-genai build with Qwen4MoePipeline for Python-side preprocessing and video input."
)
return False
return True


@dataclass
class Qwen4MoeVision:
"""Preprocessed vision inputs of one request, in prompt order per kind."""

images: List[Any] = field(default_factory=list)
videos: List[Any] = field(default_factory=list)

def __len__(self) -> int:
return len(self.images) + len(self.videos)


@dataclass
class _RawVision:
images: List[Image.Image] = field(default_factory=list)
videos: List[np.ndarray] = field(default_factory=list)
video_fps: List[Optional[float]] = field(default_factory=list)


def _data_url_bytes(url: Any, kind: str) -> bytes:
if not isinstance(url, str) or not url.startswith("data:"):
shown = url[:64] if isinstance(url, str) else type(url).__name__
raise VisionInputError(f"{kind} must be a base64 data URL (data:...;base64,...), got {shown!r}")
header, _, payload = url.partition(",")
if not payload or ";base64" not in header:
raise VisionInputError(f"{kind} data URL is not base64 encoded")
return base64.b64decode(payload)


def _decode_image(url: Any) -> Image.Image:
return Image.open(BytesIO(_data_url_bytes(url, "image_url"))).convert("RGB")


def decode_video(data: bytes) -> Tuple[np.ndarray, Optional[float]]:
"""Decode an encoded video to [frames, height, width, 3] uint8 RGB and its frame rate (None if unknown)."""
try:
import av # type: ignore[import-not-found]
except ImportError:
av = None
if av is not None:
with av.open(BytesIO(data)) as container:
stream = container.streams.video[0]
rate = stream.average_rate or stream.base_rate
frames = [frame.to_ndarray(format="rgb24") for frame in container.decode(stream)]
fps = float(rate) if rate else None
else:
try:
import cv2 # type: ignore[import-not-found]
except ImportError as exc:
raise VisionInputError("Decoding video_url needs PyAV (pip install av) or OpenCV (pip install opencv-python)") from exc
with tempfile.NamedTemporaryFile(suffix=".video") as handle:
handle.write(data)
handle.flush()
capture = cv2.VideoCapture(handle.name)
try:
fps = capture.get(cv2.CAP_PROP_FPS) or None
frames = []
while True:
ok, frame = capture.read()
if not ok:
break
frames.append(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
finally:
capture.release()
if not frames:
raise VisionInputError("video_url has no decodable frames")
return np.stack(frames), fps


def _optional_fps(value: Any) -> Optional[float]:
if value is None:
return None
fps = float(value)
if fps <= 0:
raise VisionInputError(f"fps must be positive, got {value}")
return fps


class OVGenAI_Qwen4MoeVLM(OVGenAI_VLM):
"""OVGenAI_VLM for qwen4_moe models on Qwen4MoePipeline, with images and videos preprocessed in Python."""

def __init__(self, load_config):
super().__init__(load_config)
self.processor = None

def _create_pipeline(self, model_path: str, device: str, **properties: Any) -> Any:
from openvino_genai.qwen4_moe import Qwen4MoeProcessor

pipeline = openvino_genai.Qwen4MoePipeline(model_path, device, **properties)
self.processor = Qwen4MoeProcessor(model_path)
return pipeline

def load_model(self, loader):
super().load_model(loader)
# Qwen4MoePipeline expands its own native tags; it needs no per-architecture lookup.
self.vision_token = IMAGE_TAG

def _collect_vision(self, messages: List[Dict[str, Any]]) -> Tuple[List[Dict[str, Any]], _RawVision]:
"""Decode the vision items of every message and put the native tag where each one was."""
raw = _RawVision()
text_messages: List[Dict[str, Any]] = []
for message in messages:
content = message.get("content", "")
if not isinstance(content, list):
text_messages.append({**message, "content": flatten_message_content(content)})
continue
parts: List[str] = []
for item in content:
if not isinstance(item, dict):
continue
kind = item.get("type")
if kind == "text":
parts.append(item.get("text", ""))
elif kind == "image_url":
image_url = item.get("image_url", {})
raw.images.append(_decode_image(image_url.get("url") if isinstance(image_url, dict) else image_url))
parts.append(IMAGE_TAG)
elif kind == "video_url":
video_url = item.get("video_url", {})
url = video_url.get("url") if isinstance(video_url, dict) else video_url
frames, container_fps = decode_video(_data_url_bytes(url, "video_url"))
fps = (video_url.get("fps") if isinstance(video_url, dict) else None) or item.get("fps")
raw.videos.append(frames)
raw.video_fps.append(_optional_fps(fps) or container_fps)
parts.append(VIDEO_TAG)
elif kind == "video":
frames = item.get("video")
if not isinstance(frames, list) or not frames:
raise VisionInputError("A 'video' content item needs a non-empty list of frame data URLs")
raw.videos.append(np.stack([np.asarray(_decode_image(frame)) for frame in frames]))
raw.video_fps.append(_optional_fps(item.get("fps")))
parts.append(VIDEO_TAG)
text_messages.append({**message, "content": flatten_message_content("".join(parts))})
return text_messages, raw

def _preprocess(self, raw: _RawVision) -> Qwen4MoeVision:
vision = Qwen4MoeVision()
if raw.images:
vision.images = self.processor.preprocess_images(raw.images)
if raw.videos:
vision.videos = self.processor.preprocess_videos(raw.videos, fps=raw.video_fps)
return vision

def prepare_inputs(
self,
messages: List[Dict[str, Any]],
tools: Optional[List[Dict[str, Any]]] = None,
chat_template_kwargs: dict = {},
) -> Tuple[str, Qwen4MoeVision]:
# Anything that fails before generate() is about this request's images or videos: reject the request
# (HTTP 400) and keep the model loaded.
try:
text_messages, raw = self._collect_vision(messages)
vision = self._preprocess(raw)
except VisionInputError:
raise
except Exception as exc:
raise VisionInputError(f"Could not decode or preprocess the request's images/videos: {exc}") from exc
prompt: str = self.tokenizer.apply_chat_template(
flatten_messages(text_messages),
tokenize=False,
tools=tools,
add_generation_prompt=True,
**chat_template_kwargs,
)
return prompt, vision

def _strip_stray_vision_tokens(self, prompt: str, vision: Any) -> str:
"""Drop native tags that have no input behind them (text that quotes a tag, a prompt without inputs)."""
images = len(vision.images) if isinstance(vision, Qwen4MoeVision) else len(vision)
videos = len(vision.videos) if isinstance(vision, Qwen4MoeVision) else 0
for tag, count in ((IMAGE_TAG, images), (VIDEO_TAG, videos)):
if count == 0 and tag in prompt:
logger.warning(
f"[{self.load_config.model_name}] prompt contains {prompt.count(tag)} {tag} tag(s) "
"but no matching input; stripping them"
)
prompt = prompt.replace(tag, " ")
return prompt

def _resolve_prompt_and_images(self, gen_config: OVGenAI_GenConfig) -> Tuple[str, Qwen4MoeVision]:
if gen_config.input_ids:
prompt, vision = self.tokenizer.decode(gen_config.input_ids, skip_special_tokens=False), Qwen4MoeVision()
elif gen_config.prompt:
prompt, vision = gen_config.prompt, Qwen4MoeVision()
else:
prompt, vision = self.prepare_inputs(
gen_config.messages, gen_config.tools, gen_config.chat_template_kwargs
)
return self._strip_stray_vision_tokens(prompt, vision), vision

def _vision_kwargs(self, vision: Qwen4MoeVision) -> Dict[str, Any]:
kwargs: Dict[str, Any] = {}
if vision.images:
kwargs["images"] = vision.images
if vision.videos:
kwargs["videos"] = vision.videos
return kwargs

async def unload_model(self, registry, model_name: str) -> bool:
self.processor = None
return await super().unload_model(registry, model_name)
21 changes: 15 additions & 6 deletions src/engine/ov_genai/vlm.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,14 @@ def _resolve_prompt_and_images(
prompt, images = self.prepare_inputs(gen_config.messages, gen_config.tools, gen_config.chat_template_kwargs)
return self._strip_stray_vision_tokens(prompt, images), images

def _vision_kwargs(self, vision_inputs: Any) -> Dict[str, Any]:
"""generate() keyword arguments for what _resolve_prompt_and_images returned."""
return {"images": vision_inputs} if len(vision_inputs) > 0 else {}

def _create_pipeline(self, model_path: str, device: str, **properties: Any) -> Any:
"""Build the generation pipeline. Subclasses swap in another pipeline with the same properties."""
return VLMPipeline(model_path, device, **properties)

def generate_type(self, gen_config: OVGenAI_GenConfig):
"""
Unified generation method that routes to streaming or non-streaming
Expand All @@ -203,7 +211,8 @@ async def generate_text(self, gen_config: OVGenAI_GenConfig) -> AsyncIterator[Un
ensure_tool_call_parser(gen_config, self.load_config)
generation_kwargs = self.create_generation_config(gen_config)

prompt, ov_images = self._resolve_prompt_and_images(gen_config)
# Off the event loop: decoding and preprocessing images and videos is CPU work.
prompt, ov_images = await asyncio.to_thread(self._resolve_prompt_and_images, gen_config)

# gemma4/museglimmer non-streaming: generate through the token-ID
# streamer and reconstruct the raw tagged output. Their protocol
Expand All @@ -223,7 +232,7 @@ async def generate_text(self, gen_config: OVGenAI_GenConfig) -> AsyncIterator[Un
result = await asyncio.to_thread(
self.model_path.generate,
prompt=prompt,
**({'images': ov_images} if len(ov_images) > 0 else {}),
**self._vision_kwargs(ov_images),
generation_config=generation_kwargs,
**({'streamer': streamer} if streamer is not None else {}),
)
Expand Down Expand Up @@ -265,14 +274,14 @@ async def generate_stream(self,
self._active_request_id = gen_config.request_id
self._active_streamer = streamer

prompt, ov_images = self._resolve_prompt_and_images(gen_config)
prompt, ov_images = await asyncio.to_thread(self._resolve_prompt_and_images, gen_config)

async def _run_generation():
try:
return await asyncio.to_thread(
self.model_path.generate,
prompt=prompt,
**({'images': ov_images} if len(ov_images) > 0 else {}),
**self._vision_kwargs(ov_images),
generation_config=generation_kwargs,
streamer=streamer,
)
Expand Down Expand Up @@ -406,7 +415,7 @@ def load_model(self, loader: ModelLoadConfig):
if draft_model is not None:
pipeline_kwargs['draft_model'] = draft_model

self.model_path = VLMPipeline(
self.model_path = self._create_pipeline(
loader.model_path,
loader.device,
**scheduler_config,
Expand All @@ -420,7 +429,7 @@ def load_model(self, loader: ModelLoadConfig):
logger.info(f"{loader.model_name} loaded successfully")

except Exception as e:
logger.error(f"[{loader.model_name}] Failed to initialize VLMPipeline: {e}", exc_info=True)
logger.error(f"[{loader.model_name}] Failed to initialize {type(self).__name__}: {e}", exc_info=True)
raise

async def unload_model(self, registry: ModelRegistry, model_name: str) -> bool:
Expand Down
5 changes: 5 additions & 0 deletions src/engine/vision.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
"""Vision helpers shared by the VLM engines."""


class VisionInputError(ValueError):
"""The request carried an image or video that cannot be decoded or preprocessed: a client error, not a model failure."""
Loading