[Model] Add Moondream3 model support(only query and caption skills) (#32325)
Signed-off-by: Dong Wang <dongw2019@gmail.com>
This commit is contained in:
@@ -805,6 +805,32 @@ VLM_TEST_SETTINGS = {
|
||||
max_num_seqs=2,
|
||||
patch_hf_runner=model_utils.molmo_patch_hf_runner,
|
||||
),
|
||||
"moondream3": VLMTestInfo(
|
||||
models=["moondream/moondream3-preview"],
|
||||
test_type=VLMTestType.IMAGE,
|
||||
prompt_formatter=identity,
|
||||
img_idx_to_prompt=lambda idx: "<|endoftext|><image>",
|
||||
# Common-image coverage here targets query/caption. The native
|
||||
# detect/point skills are not exposed by vLLM.
|
||||
single_image_prompts=IMAGE_ASSETS.prompts(
|
||||
{
|
||||
"stop_sign": "<vlm_image><|md_reserved_0|>query<|md_reserved_1|>What is this sign?<|md_reserved_2|>", # noqa: E501
|
||||
"cherry_blossom": (
|
||||
"<vlm_image><|md_reserved_0|>query<|md_reserved_1|>What season is shown?<|md_reserved_2|>" # noqa: E501
|
||||
),
|
||||
}
|
||||
),
|
||||
max_model_len=4096,
|
||||
max_num_seqs=2,
|
||||
dtype="bfloat16",
|
||||
hf_processor=model_utils.moondream3_processor,
|
||||
patch_hf_runner=model_utils.moondream3_patch_hf_runner,
|
||||
# Single size factor to avoid GPU OOM when running multiple test
|
||||
# cases sequentially (9B MoE model uses ~18 GiB per instance).
|
||||
image_size_factors=[(1.0,)],
|
||||
# Moondream3 is 9B params with MoE, needs significant GPU memory
|
||||
marks=[large_gpu_mark(min_gb=48)],
|
||||
),
|
||||
"ovis1_6-gemma2": VLMTestInfo(
|
||||
models=["AIDC-AI/Ovis1.6-Gemma2-9B"],
|
||||
test_type=(VLMTestType.IMAGE, VLMTestType.MULTI_IMAGE),
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Generation tests for Moondream3 query and caption support."""
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.models.registry import HF_EXAMPLE_MODELS
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
from ....conftest import IMAGE_ASSETS, ImageTestAssets
|
||||
from ....utils import large_gpu_mark, multi_gpu_test
|
||||
|
||||
MOONDREAM3_MODEL_ID = "moondream/moondream3-preview"
|
||||
MOONDREAM3_TOKENIZER = "moondream/starmie-v1"
|
||||
|
||||
HF_IMAGE_PROMPTS = IMAGE_ASSETS.prompts(
|
||||
{
|
||||
"stop_sign": "<|endoftext|><image><|md_reserved_0|>query<|md_reserved_1|>What color is the stop sign?<|md_reserved_2|>", # noqa: E501
|
||||
"cherry_blossom": "<|endoftext|><image><|md_reserved_0|>query<|md_reserved_1|>What color are the flowers?<|md_reserved_2|>", # noqa: E501
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def make_query_prompt(question: str) -> str:
|
||||
"""Create a direct-answer query prompt for Moondream3."""
|
||||
return (
|
||||
"<|endoftext|><image><|md_reserved_0|>query<|md_reserved_1|>"
|
||||
f"{question}<|md_reserved_2|>"
|
||||
)
|
||||
|
||||
|
||||
def make_caption_prompt(length: str = "normal") -> str:
|
||||
"""Create a caption prompt for Moondream3."""
|
||||
return (
|
||||
"<|endoftext|><image><|md_reserved_0|>"
|
||||
f"describe<|md_reserved_1|>{length}<|md_reserved_2|>"
|
||||
)
|
||||
|
||||
|
||||
@multi_gpu_test(num_gpus=2)
|
||||
@large_gpu_mark(min_gb=80)
|
||||
def test_tensor_parallel(image_assets: ImageTestAssets):
|
||||
import gc
|
||||
|
||||
from vllm import LLM, SamplingParams
|
||||
from vllm.distributed.parallel_state import destroy_model_parallel
|
||||
|
||||
destroy_model_parallel()
|
||||
gc.collect()
|
||||
current_platform.empty_cache()
|
||||
|
||||
llm = LLM(
|
||||
model=MOONDREAM3_MODEL_ID,
|
||||
tokenizer=MOONDREAM3_TOKENIZER,
|
||||
trust_remote_code=True,
|
||||
dtype="bfloat16",
|
||||
tensor_parallel_size=2,
|
||||
max_model_len=1024,
|
||||
enforce_eager=True,
|
||||
limit_mm_per_prompt={"image": 1},
|
||||
gpu_memory_utilization=0.45,
|
||||
)
|
||||
|
||||
image = image_assets[0].pil_image
|
||||
prompt = make_query_prompt("What color is the stop sign?")
|
||||
|
||||
try:
|
||||
outputs = llm.generate(
|
||||
{"prompt": prompt, "multi_modal_data": {"image": image}},
|
||||
SamplingParams(max_tokens=20, temperature=0),
|
||||
)
|
||||
|
||||
assert len(outputs) > 0
|
||||
assert outputs[0].outputs[0].text is not None
|
||||
finally:
|
||||
del llm
|
||||
gc.collect()
|
||||
current_platform.empty_cache()
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def llm():
|
||||
model_info = HF_EXAMPLE_MODELS.get_hf_info("Moondream3ForCausalLM")
|
||||
model_info.check_transformers_version(on_fail="skip")
|
||||
|
||||
from vllm import LLM
|
||||
|
||||
try:
|
||||
return LLM(
|
||||
model=MOONDREAM3_MODEL_ID,
|
||||
tokenizer=MOONDREAM3_TOKENIZER,
|
||||
trust_remote_code=True,
|
||||
dtype="bfloat16",
|
||||
max_model_len=2048,
|
||||
enforce_eager=True,
|
||||
limit_mm_per_prompt={"image": 1},
|
||||
gpu_memory_utilization=0.45,
|
||||
)
|
||||
except Exception as exc:
|
||||
pytest.skip(f"Failed to load {MOONDREAM3_MODEL_ID}: {exc}")
|
||||
|
||||
|
||||
@large_gpu_mark(min_gb=48)
|
||||
def test_model_loading(llm):
|
||||
assert llm is not None
|
||||
|
||||
|
||||
@large_gpu_mark(min_gb=48)
|
||||
def test_query_skill(llm, image_assets: ImageTestAssets):
|
||||
from vllm import SamplingParams
|
||||
|
||||
image = image_assets[0].pil_image
|
||||
prompt = make_query_prompt("What color is the stop sign?")
|
||||
|
||||
outputs = llm.generate(
|
||||
{"prompt": prompt, "multi_modal_data": {"image": image}},
|
||||
SamplingParams(max_tokens=50, temperature=0),
|
||||
)
|
||||
|
||||
output_text = outputs[0].outputs[0].text
|
||||
assert output_text is not None
|
||||
assert len(output_text) > 0
|
||||
|
||||
|
||||
@large_gpu_mark(min_gb=48)
|
||||
def test_caption_skill(llm, image_assets: ImageTestAssets):
|
||||
from vllm import SamplingParams
|
||||
|
||||
image = image_assets[1].pil_image
|
||||
prompt = make_caption_prompt()
|
||||
|
||||
outputs = llm.generate(
|
||||
{"prompt": prompt, "multi_modal_data": {"image": image}},
|
||||
SamplingParams(max_tokens=100, temperature=0),
|
||||
)
|
||||
|
||||
output_text = outputs[0].outputs[0].text
|
||||
assert output_text is not None
|
||||
assert len(output_text) > 0
|
||||
|
||||
|
||||
@large_gpu_mark(min_gb=48)
|
||||
def test_batched_inference(llm, image_assets: ImageTestAssets):
|
||||
from vllm import SamplingParams
|
||||
|
||||
images = [asset.pil_image for asset in image_assets]
|
||||
prompts = [
|
||||
{"prompt": prompt, "multi_modal_data": {"image": img}}
|
||||
for img, prompt in zip(images, HF_IMAGE_PROMPTS)
|
||||
]
|
||||
|
||||
outputs = llm.generate(prompts, SamplingParams(max_tokens=50, temperature=0))
|
||||
|
||||
assert len(outputs) == len(images)
|
||||
for output in outputs:
|
||||
assert output.outputs[0].text is not None
|
||||
assert len(output.outputs[0].text) > 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize("asset_name", ["stop_sign", "cherry_blossom"])
|
||||
@large_gpu_mark(min_gb=48)
|
||||
def test_image_assets(llm, image_assets: ImageTestAssets, asset_name: str):
|
||||
from vllm import SamplingParams
|
||||
|
||||
asset_idx = 0 if asset_name == "stop_sign" else 1
|
||||
image = image_assets[asset_idx].pil_image
|
||||
prompt = HF_IMAGE_PROMPTS[asset_idx]
|
||||
|
||||
outputs = llm.generate(
|
||||
{"prompt": prompt, "multi_modal_data": {"image": image}},
|
||||
SamplingParams(max_tokens=50, temperature=0),
|
||||
)
|
||||
|
||||
output_text = outputs[0].outputs[0].text
|
||||
assert output_text is not None
|
||||
assert len(output_text) > 0
|
||||
@@ -38,6 +38,7 @@ def run_test(
|
||||
limit_mm_per_prompt: dict[str, int],
|
||||
vllm_runner_kwargs: dict[str, Any] | None,
|
||||
hf_model_kwargs: dict[str, Any] | None,
|
||||
hf_processor: Callable[[str], Any] | None,
|
||||
patch_hf_runner: Callable[[HfRunner], HfRunner] | None,
|
||||
runner: RunnerOption = "auto",
|
||||
distributed_executor_backend: str | None = None,
|
||||
@@ -116,8 +117,18 @@ def run_test(
|
||||
)
|
||||
vllm_outputs_per_mm.append(vllm_output)
|
||||
|
||||
hf_runner_kwargs: dict[str, Any] = {}
|
||||
if model_info.tokenizer:
|
||||
hf_runner_kwargs["tokenizer_name"] = model_info.tokenizer
|
||||
if hf_processor is not None:
|
||||
hf_runner_kwargs["processor"] = hf_processor(model)
|
||||
|
||||
hf_model = hf_runner(
|
||||
model, dtype=dtype, auto_cls=auto_cls, model_kwargs=hf_model_kwargs
|
||||
model,
|
||||
dtype=dtype,
|
||||
auto_cls=auto_cls,
|
||||
model_kwargs=hf_model_kwargs,
|
||||
**hf_runner_kwargs,
|
||||
)
|
||||
|
||||
# Some models need to patch things like the model processor, e.g., internvl
|
||||
|
||||
@@ -1336,3 +1336,221 @@ def voxtral_patch_hf_runner(hf_model: "HfRunner") -> "HfRunner":
|
||||
hf_model.get_inputs = patched_get_inputs # type: ignore[method-assign, assignment]
|
||||
hf_model.model.generate = patched_generate # type: ignore[method-assign]
|
||||
return hf_model
|
||||
|
||||
|
||||
def moondream3_processor(model: str):
|
||||
from vllm.transformers_utils.processors.moondream3 import Moondream3Processor
|
||||
|
||||
return Moondream3Processor.from_pretrained(model, trust_remote_code=True)
|
||||
|
||||
|
||||
def moondream3_patch_hf_runner(hf_model: HfRunner) -> HfRunner:
|
||||
"""Patch HfRunner for Moondream3."""
|
||||
moondream_processor = hf_model.processor
|
||||
|
||||
def processor(*args, text="", images=None, **kwargs):
|
||||
if images is None:
|
||||
return moondream_processor(text=text, **kwargs)
|
||||
|
||||
images_list = [images] if isinstance(images, Image) else images
|
||||
return moondream_processor(images=images_list, text=text, **kwargs)
|
||||
|
||||
hf_model.processor = processor
|
||||
|
||||
# Expose the LM head for logprob extraction.
|
||||
hf_model.model.get_output_embeddings = lambda: hf_model.model.model.text.lm_head
|
||||
|
||||
native_model = hf_model.model.model # MoondreamModel instance
|
||||
|
||||
from torch.nn import functional as F
|
||||
|
||||
from vllm.model_executor.models.moondream3 import reconstruct_from_crops
|
||||
|
||||
# Resolve the placeholder tokens from the tokenizer instead of hard-coding.
|
||||
image_placeholder_ids = moondream_processor.tokenizer.encode(
|
||||
"<image>", add_special_tokens=False
|
||||
)
|
||||
|
||||
def _normalize_tiling(tilings):
|
||||
"""Extract (h, w) tuple from various tiling container formats."""
|
||||
tiling = tilings
|
||||
if isinstance(tiling, torch.Tensor):
|
||||
tiling = tuple(tiling.squeeze().tolist())
|
||||
elif isinstance(tiling, (list, tuple)):
|
||||
t0 = tiling[0]
|
||||
if isinstance(t0, torch.Tensor):
|
||||
tiling = tuple(t0.tolist())
|
||||
elif isinstance(t0, (list, tuple)):
|
||||
tiling = tuple(t0)
|
||||
return tiling
|
||||
|
||||
def _encode_vision(pixel_values, tilings):
|
||||
"""Run preprocessed crops through vision encoder + projection."""
|
||||
device = native_model.device
|
||||
dtype = native_model.vision.pos_emb.dtype
|
||||
config = native_model.config
|
||||
|
||||
pv = pixel_values
|
||||
while pv.dim() > 4:
|
||||
pv = pv.squeeze(0)
|
||||
pv = pv.to(device=device, dtype=dtype)
|
||||
|
||||
features = native_model._vis_enc(pv)
|
||||
grid_size = config.vision.crop_size // config.vision.enc_patch_size
|
||||
global_feat = features[0]
|
||||
|
||||
if features.shape[0] > 1 and tilings is not None:
|
||||
tiling = _normalize_tiling(tilings)
|
||||
local = features[1:].view(-1, grid_size, grid_size, config.vision.enc_dim)
|
||||
reconstructed = reconstruct_from_crops(
|
||||
local,
|
||||
tiling,
|
||||
config.vision.overlap_margin,
|
||||
patch_size=1,
|
||||
)
|
||||
else:
|
||||
reconstructed = global_feat.view(
|
||||
grid_size, grid_size, config.vision.enc_dim
|
||||
)
|
||||
|
||||
return native_model._vis_proj(global_feat, reconstructed)
|
||||
|
||||
def _find_subsequence(seq, subseq):
|
||||
"""Find start index of subseq in seq, or None."""
|
||||
n = len(subseq)
|
||||
for i in range(len(seq) - n + 1):
|
||||
if seq[i : i + n] == subseq:
|
||||
return i
|
||||
return None
|
||||
|
||||
def _generate(
|
||||
self,
|
||||
input_ids=None,
|
||||
pixel_values=None,
|
||||
tilings=None,
|
||||
attention_mask=None,
|
||||
**kwargs,
|
||||
):
|
||||
max_new_tokens = kwargs.get("max_new_tokens", 128)
|
||||
return_dict = kwargs.get("return_dict_in_generate", False)
|
||||
output_hs = kwargs.get("output_hidden_states", False)
|
||||
|
||||
if pixel_values is None:
|
||||
sequences = input_ids
|
||||
if return_dict:
|
||||
return types.SimpleNamespace(
|
||||
sequences=sequences,
|
||||
hidden_states=() if output_hs else None,
|
||||
)
|
||||
return sequences
|
||||
|
||||
# Processor may return lists; extract the single element.
|
||||
if isinstance(pixel_values, (list, tuple)):
|
||||
pixel_values = pixel_values[0]
|
||||
if (
|
||||
isinstance(tilings, (list, tuple))
|
||||
and tilings
|
||||
and not isinstance(tilings[0], int)
|
||||
):
|
||||
tilings = tilings[0]
|
||||
|
||||
hf_model.model._setup_caches()
|
||||
native_model.use_flex_decoding = False
|
||||
|
||||
device = native_model.device
|
||||
config = native_model.config
|
||||
|
||||
with torch.inference_mode():
|
||||
for block in native_model.text.blocks:
|
||||
block.kv_cache.k_cache.zero_()
|
||||
block.kv_cache.v_cache.zero_()
|
||||
|
||||
img_emb = _encode_vision(pixel_values, tilings)
|
||||
|
||||
bos_emb = F.embedding(
|
||||
torch.tensor([[config.tokenizer.bos_id]], device=device),
|
||||
native_model.text.wte,
|
||||
)
|
||||
img_input = torch.cat([bos_emb, img_emb.unsqueeze(0)], dim=1)
|
||||
prefix_len = img_input.size(1)
|
||||
|
||||
mask = native_model.attn_mask[:, :, :prefix_len, :]
|
||||
pos_ids = torch.arange(prefix_len, dtype=torch.long, device=device)
|
||||
native_model._prefill(img_input, mask, pos_ids, None)
|
||||
|
||||
ids = input_ids.squeeze(0).tolist()
|
||||
img_start = _find_subsequence(ids, image_placeholder_ids)
|
||||
|
||||
if img_start is None:
|
||||
sequences = input_ids
|
||||
if return_dict:
|
||||
return types.SimpleNamespace(
|
||||
sequences=sequences,
|
||||
hidden_states=() if output_hs else None,
|
||||
)
|
||||
return sequences
|
||||
|
||||
prompt_tokens = ids[img_start + len(image_placeholder_ids) :]
|
||||
|
||||
if not prompt_tokens:
|
||||
sequences = input_ids
|
||||
if return_dict:
|
||||
return types.SimpleNamespace(
|
||||
sequences=sequences,
|
||||
hidden_states=() if output_hs else None,
|
||||
)
|
||||
return sequences
|
||||
|
||||
prompt_tensor = torch.tensor([prompt_tokens], device=device)
|
||||
prompt_emb = F.embedding(prompt_tensor, native_model.text.wte)
|
||||
prompt_len = prompt_emb.size(1)
|
||||
|
||||
mask = native_model.attn_mask[:, :, prefix_len : prefix_len + prompt_len, :]
|
||||
pos_ids = torch.arange(
|
||||
prefix_len,
|
||||
prefix_len + prompt_len,
|
||||
dtype=torch.long,
|
||||
device=device,
|
||||
)
|
||||
hidden = native_model._prefill(prompt_emb, mask, pos_ids, None)
|
||||
pos = prefix_len + prompt_len
|
||||
|
||||
hidden_last = native_model.text.post_ln(hidden[:, -1:, :])
|
||||
logits = native_model.text.lm_head(hidden_last.squeeze(1))
|
||||
|
||||
generated = []
|
||||
all_hidden_states = []
|
||||
# Record the hidden state that predicted each generated token.
|
||||
prev_hs = hidden_last
|
||||
for _ in range(max_new_tokens):
|
||||
next_token = logits.argmax(dim=-1).item()
|
||||
if next_token == 0:
|
||||
break
|
||||
generated.append(next_token)
|
||||
if output_hs:
|
||||
all_hidden_states.append((prev_hs,))
|
||||
|
||||
next_emb = F.embedding(
|
||||
torch.tensor([[next_token]], device=device),
|
||||
native_model.text.wte,
|
||||
)
|
||||
mask = native_model.attn_mask[:, :, pos : pos + 1, :]
|
||||
pos_ids_step = torch.tensor([pos], dtype=torch.long, device=device)
|
||||
hidden = native_model._prefill(next_emb, mask, pos_ids_step, None)
|
||||
hidden_last = native_model.text.post_ln(hidden[:, -1:, :])
|
||||
prev_hs = hidden_last
|
||||
logits = native_model.text.lm_head(hidden_last.squeeze(1))
|
||||
pos += 1
|
||||
|
||||
result_ids = ids + generated
|
||||
sequences = torch.tensor([result_ids], device=device)
|
||||
|
||||
if return_dict:
|
||||
return types.SimpleNamespace(
|
||||
sequences=sequences,
|
||||
hidden_states=tuple(all_hidden_states) if output_hs else None,
|
||||
)
|
||||
return sequences
|
||||
|
||||
hf_model.model.generate = types.MethodType(_generate, hf_model.model)
|
||||
return hf_model
|
||||
|
||||
@@ -133,6 +133,7 @@ class VLMTestInfo(NamedTuple):
|
||||
|
||||
# Exposed options for HF runner
|
||||
hf_model_kwargs: dict[str, Any] | None = None
|
||||
hf_processor: Callable[[str], Any] | None = None
|
||||
# Indicates we should explicitly pass the EOS from the tokenizer
|
||||
use_tokenizer_eos: bool = False
|
||||
auto_cls: type[_BaseAutoModelClass] = AutoModelForCausalLM
|
||||
@@ -196,6 +197,7 @@ class VLMTestInfo(NamedTuple):
|
||||
"comparator": self.comparator,
|
||||
"get_stop_token_ids": self.get_stop_token_ids,
|
||||
"hf_model_kwargs": self.hf_model_kwargs,
|
||||
"hf_processor": self.hf_processor,
|
||||
"stop_str": self.stop_str,
|
||||
"patch_hf_runner": self.patch_hf_runner,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,553 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Tests for Moondream3 multimodal processing.
|
||||
|
||||
Includes:
|
||||
- Processor creation and application tests
|
||||
- Image tokenization and placeholder expansion tests
|
||||
- Tiling and cropping logic tests (CPU-based)
|
||||
- Pixel normalization tests
|
||||
"""
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
|
||||
from ....conftest import ImageTestAssets
|
||||
from ...utils import build_model_context
|
||||
|
||||
MOONDREAM3_MODEL_ID = "moondream/moondream3-preview"
|
||||
# Expected multimodal prefix: BOS + 729 image tokens.
|
||||
EXPECTED_IMAGE_TOKENS = 730
|
||||
# Vision encoder constants
|
||||
CROP_SIZE = 378
|
||||
PATCH_SIZE = 14
|
||||
MAX_CROPS = 12
|
||||
|
||||
|
||||
@pytest.mark.parametrize("model_id", [MOONDREAM3_MODEL_ID])
|
||||
def test_processor_creation(model_id: str):
|
||||
"""Test that Moondream3 processor can be created."""
|
||||
ctx = build_model_context(
|
||||
model_id,
|
||||
limit_mm_per_prompt={"image": 1},
|
||||
)
|
||||
processor = MULTIMODAL_REGISTRY.create_processor(ctx.model_config)
|
||||
assert processor is not None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("model_id", [MOONDREAM3_MODEL_ID])
|
||||
def test_processor_apply(
|
||||
image_assets: ImageTestAssets,
|
||||
model_id: str,
|
||||
):
|
||||
"""Test that Moondream3 processor can process inputs.
|
||||
|
||||
NOTE: The prompt includes the leading BOS token because Moondream3
|
||||
pre-fills BOS and image embeddings together.
|
||||
"""
|
||||
ctx = build_model_context(
|
||||
model_id,
|
||||
limit_mm_per_prompt={"image": 1},
|
||||
)
|
||||
processor = MULTIMODAL_REGISTRY.create_processor(ctx.model_config)
|
||||
|
||||
prompt = "<|endoftext|><image><|md_reserved_0|>query<|md_reserved_1|>What is this?<|md_reserved_2|>" # noqa: E501
|
||||
mm_data = {"image": [image_assets[0].pil_image]}
|
||||
|
||||
processed_inputs = processor(
|
||||
prompt,
|
||||
mm_items=processor.info.parse_mm_data(mm_data),
|
||||
hf_processor_mm_kwargs={},
|
||||
)
|
||||
|
||||
assert "prompt_token_ids" in processed_inputs
|
||||
image_placeholders = processed_inputs["mm_placeholders"]["image"]
|
||||
assert len(image_placeholders) == 1
|
||||
assert image_placeholders[0].length == EXPECTED_IMAGE_TOKENS
|
||||
|
||||
|
||||
@pytest.mark.parametrize("model_id", [MOONDREAM3_MODEL_ID])
|
||||
def test_processor_pixel_values(
|
||||
image_assets: ImageTestAssets,
|
||||
model_id: str,
|
||||
):
|
||||
"""Test that pixel values are correctly produced."""
|
||||
ctx = build_model_context(
|
||||
model_id,
|
||||
limit_mm_per_prompt={"image": 1},
|
||||
)
|
||||
processor = MULTIMODAL_REGISTRY.create_processor(ctx.model_config)
|
||||
|
||||
prompt = "<|endoftext|><image><|md_reserved_0|>query<|md_reserved_1|>What is this?<|md_reserved_2|>" # noqa: E501
|
||||
mm_data = {"image": [image_assets[0].pil_image]}
|
||||
|
||||
processed_inputs = processor(
|
||||
prompt,
|
||||
mm_items=processor.info.parse_mm_data(mm_data),
|
||||
hf_processor_mm_kwargs={},
|
||||
)
|
||||
|
||||
# Check mm_kwargs contains pixel_values
|
||||
mm_kwargs = processed_inputs.get("mm_kwargs")
|
||||
assert mm_kwargs is not None
|
||||
mm_data_result = mm_kwargs.get_data()
|
||||
assert "pixel_values" in mm_data_result
|
||||
|
||||
# Verify pixel_values shape
|
||||
pixel_values = mm_data_result["pixel_values"]
|
||||
assert pixel_values.dim() == 5 # [batch, num_crops, C, H, W]
|
||||
assert pixel_values.shape[2] == 3 # RGB channels
|
||||
assert pixel_values.shape[3] == 378 # crop height
|
||||
assert pixel_values.shape[4] == 378 # crop width
|
||||
|
||||
|
||||
@pytest.mark.parametrize("model_id", [MOONDREAM3_MODEL_ID])
|
||||
def test_processor_image_token_expansion(
|
||||
image_assets: ImageTestAssets,
|
||||
model_id: str,
|
||||
):
|
||||
"""Test that <image> placeholder is expanded to correct number of tokens."""
|
||||
ctx = build_model_context(
|
||||
model_id,
|
||||
limit_mm_per_prompt={"image": 1},
|
||||
)
|
||||
processor = MULTIMODAL_REGISTRY.create_processor(ctx.model_config)
|
||||
|
||||
prompt = "<|endoftext|><image><|md_reserved_0|>query<|md_reserved_1|>Describe.<|md_reserved_2|>" # noqa: E501
|
||||
mm_data = {"image": [image_assets[0].pil_image]}
|
||||
|
||||
processed_inputs = processor(
|
||||
prompt,
|
||||
mm_items=processor.info.parse_mm_data(mm_data),
|
||||
hf_processor_mm_kwargs={},
|
||||
)
|
||||
image_placeholders = processed_inputs["mm_placeholders"]["image"]
|
||||
assert len(image_placeholders) == 1
|
||||
assert image_placeholders[0].length == EXPECTED_IMAGE_TOKENS
|
||||
|
||||
|
||||
@pytest.mark.parametrize("model_id", [MOONDREAM3_MODEL_ID])
|
||||
def test_multi_crop_tiling(
|
||||
model_id: str,
|
||||
):
|
||||
"""Test that large images produce correct multi-crop tiling."""
|
||||
from PIL import Image
|
||||
|
||||
from vllm.transformers_utils.processors.moondream3 import Moondream3Processor
|
||||
|
||||
processor = Moondream3Processor.from_pretrained(model_id, trust_remote_code=True)
|
||||
|
||||
# Create a large image that requires multiple crops
|
||||
large_image = Image.new("RGB", (1000, 1000), color="blue")
|
||||
pixel_values, tiling = processor.preprocess_image(large_image)
|
||||
|
||||
# Large images should produce more than 1x1 tiling
|
||||
assert tiling[0] >= 1 and tiling[1] >= 1
|
||||
# Check that we have global crop + local crops
|
||||
expected_crops = tiling[0] * tiling[1] + 1
|
||||
assert pixel_values.shape[0] == expected_crops
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"image_size",
|
||||
[
|
||||
(500, 500),
|
||||
(800, 600),
|
||||
(1920, 1080),
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize("model_id", [MOONDREAM3_MODEL_ID])
|
||||
def test_tiling_various_sizes(
|
||||
image_size: tuple[int, int],
|
||||
model_id: str,
|
||||
):
|
||||
"""Test tiling with various image sizes."""
|
||||
from PIL import Image
|
||||
|
||||
from vllm.transformers_utils.processors.moondream3 import Moondream3Processor
|
||||
|
||||
processor = Moondream3Processor.from_pretrained(model_id, trust_remote_code=True)
|
||||
|
||||
width, height = image_size
|
||||
image = Image.new("RGB", (width, height), color="red")
|
||||
pixel_values, tiling = processor.preprocess_image(image)
|
||||
|
||||
# Basic shape checks
|
||||
assert pixel_values.dim() == 4 # [num_crops, C, H, W]
|
||||
assert pixel_values.shape[1] == 3 # RGB
|
||||
assert pixel_values.shape[2] == 378 # crop height
|
||||
assert pixel_values.shape[3] == 378 # crop width
|
||||
|
||||
# Tiling should respect max_crops (12)
|
||||
assert tiling[0] * tiling[1] <= 12
|
||||
|
||||
|
||||
@pytest.mark.parametrize("model_id", [MOONDREAM3_MODEL_ID])
|
||||
def test_pixel_normalization(
|
||||
model_id: str,
|
||||
):
|
||||
"""Test that pixel values are normalized to [-1, 1] range."""
|
||||
from PIL import Image
|
||||
|
||||
from vllm.transformers_utils.processors.moondream3 import Moondream3Processor
|
||||
|
||||
processor = Moondream3Processor.from_pretrained(model_id, trust_remote_code=True)
|
||||
|
||||
# Create test image
|
||||
image = Image.new("RGB", (378, 378), color="green")
|
||||
pixel_values, _ = processor.preprocess_image(image)
|
||||
|
||||
# Normalization: (x - 0.5) / 0.5 = 2*x - 1
|
||||
# For input [0, 1], output should be [-1, 1]
|
||||
assert pixel_values.min() >= -1.0
|
||||
assert pixel_values.max() <= 1.0
|
||||
|
||||
|
||||
@pytest.mark.parametrize("model_id", [MOONDREAM3_MODEL_ID])
|
||||
def test_chat_template_with_image(
|
||||
image_assets: ImageTestAssets,
|
||||
model_id: str,
|
||||
):
|
||||
"""Test that chat template correctly formats BOS + image + prompt."""
|
||||
ctx = build_model_context(
|
||||
model_id,
|
||||
limit_mm_per_prompt={"image": 1},
|
||||
)
|
||||
processor = MULTIMODAL_REGISTRY.create_processor(ctx.model_config)
|
||||
tokenizer = ctx.tokenizer
|
||||
|
||||
# Use the chat template format
|
||||
prompt = "<|endoftext|><image><|md_reserved_0|>query<|md_reserved_1|>What is this?<|md_reserved_2|>" # noqa: E501
|
||||
mm_data = {"image": [image_assets[0].pil_image]}
|
||||
|
||||
processed_inputs = processor(
|
||||
prompt,
|
||||
mm_items=processor.info.parse_mm_data(mm_data),
|
||||
hf_processor_mm_kwargs={},
|
||||
)
|
||||
token_ids = processed_inputs["prompt_token_ids"]
|
||||
|
||||
# BOS token (<|endoftext|>) should be token ID 0
|
||||
bos_token_id = tokenizer.encode("<|endoftext|>", add_special_tokens=False)[0]
|
||||
assert bos_token_id == 0
|
||||
|
||||
# First token should be BOS
|
||||
assert token_ids[0] == bos_token_id
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"content",
|
||||
[
|
||||
pytest.param(
|
||||
[
|
||||
{
|
||||
"type": "image_url",
|
||||
"image_url": {"url": "https://example.invalid/image.png"},
|
||||
},
|
||||
{"type": "text", "text": "What is in this image?"},
|
||||
],
|
||||
id="image-first",
|
||||
),
|
||||
pytest.param(
|
||||
[
|
||||
{"type": "text", "text": "What is in this image?"},
|
||||
{
|
||||
"type": "image_url",
|
||||
"image_url": {"url": "https://example.invalid/image.png"},
|
||||
},
|
||||
],
|
||||
id="text-first",
|
||||
),
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize("model_id", [MOONDREAM3_MODEL_ID])
|
||||
def test_chat_template_content_list_uses_moondream_image_prefix(
|
||||
image_assets: ImageTestAssets,
|
||||
content: list[dict[str, object]],
|
||||
model_id: str,
|
||||
):
|
||||
ctx = build_model_context(
|
||||
model_id,
|
||||
limit_mm_per_prompt={"image": 1},
|
||||
)
|
||||
processor = MULTIMODAL_REGISTRY.create_processor(ctx.model_config)
|
||||
hf_processor = processor.info.get_hf_processor()
|
||||
|
||||
prompt = hf_processor.tokenizer.apply_chat_template(
|
||||
[{"role": "user", "content": content}],
|
||||
chat_template=hf_processor.chat_template,
|
||||
tokenize=False,
|
||||
)
|
||||
|
||||
expected_prompt = (
|
||||
"<|endoftext|><image><|md_reserved_0|>query<|md_reserved_1|>"
|
||||
"What is in this image?<|md_reserved_2|>"
|
||||
)
|
||||
assert prompt == expected_prompt
|
||||
|
||||
processed_inputs = processor(
|
||||
prompt,
|
||||
mm_items=processor.info.parse_mm_data({"image": [image_assets[0].pil_image]}),
|
||||
hf_processor_mm_kwargs={},
|
||||
)
|
||||
image_placeholders = processed_inputs["mm_placeholders"]["image"]
|
||||
assert len(image_placeholders) == 1
|
||||
assert image_placeholders[0].length == EXPECTED_IMAGE_TOKENS
|
||||
|
||||
|
||||
@pytest.mark.parametrize("model_id", [MOONDREAM3_MODEL_ID])
|
||||
def test_bos_token_always_first(
|
||||
image_assets: ImageTestAssets,
|
||||
model_id: str,
|
||||
):
|
||||
"""Test that BOS token (ID 0) is always at position 0."""
|
||||
ctx = build_model_context(
|
||||
model_id,
|
||||
limit_mm_per_prompt={"image": 1},
|
||||
)
|
||||
processor = MULTIMODAL_REGISTRY.create_processor(ctx.model_config)
|
||||
|
||||
# Start with BOS token explicitly
|
||||
prompt = "<|endoftext|><image><|md_reserved_0|>query<|md_reserved_1|>Describe this image.<|md_reserved_2|>" # noqa: E501
|
||||
mm_data = {"image": [image_assets[0].pil_image]}
|
||||
|
||||
processed_inputs = processor(
|
||||
prompt,
|
||||
mm_items=processor.info.parse_mm_data(mm_data),
|
||||
hf_processor_mm_kwargs={},
|
||||
)
|
||||
token_ids = processed_inputs["prompt_token_ids"]
|
||||
|
||||
# Token ID 0 (<|endoftext|>) should be the first token
|
||||
assert token_ids[0] == 0, (
|
||||
f"Expected BOS token (0) at position 0, got {token_ids[0]}"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("model_id", [MOONDREAM3_MODEL_ID])
|
||||
def test_processor_with_small_image(
|
||||
model_id: str,
|
||||
):
|
||||
"""Test processor with image smaller than crop size."""
|
||||
from PIL import Image
|
||||
|
||||
from vllm.transformers_utils.processors.moondream3 import Moondream3Processor
|
||||
|
||||
processor = Moondream3Processor.from_pretrained(model_id, trust_remote_code=True)
|
||||
|
||||
# Small image (smaller than crop size)
|
||||
small_image = Image.new("RGB", (100, 100), color="yellow")
|
||||
pixel_values, tiling = processor.preprocess_image(small_image)
|
||||
|
||||
# Small images should use 1x1 tiling
|
||||
assert tiling == (1, 1)
|
||||
# Should have 2 crops (global + 1 local)
|
||||
assert pixel_values.shape[0] == 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"image_kind",
|
||||
[
|
||||
pytest.param("numpy_hwc", id="numpy-hwc"),
|
||||
pytest.param("numpy_chw", id="numpy-chw"),
|
||||
pytest.param("torch_chw", id="torch-chw"),
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize("model_id", [MOONDREAM3_MODEL_ID])
|
||||
def test_preprocess_image_accepts_non_pil_inputs(
|
||||
image_assets: ImageTestAssets,
|
||||
image_kind: str,
|
||||
model_id: str,
|
||||
):
|
||||
from vllm.transformers_utils.processors.moondream3 import Moondream3Processor
|
||||
|
||||
processor = Moondream3Processor.from_pretrained(model_id, trust_remote_code=True)
|
||||
pil_image = image_assets[0].pil_image.convert("RGB")
|
||||
hwc_array = np.asarray(pil_image)
|
||||
expected_pixel_values, expected_tiling = processor.preprocess_image(pil_image)
|
||||
|
||||
if image_kind == "numpy_hwc":
|
||||
image = hwc_array
|
||||
elif image_kind == "numpy_chw":
|
||||
image = np.transpose(hwc_array, (2, 0, 1))
|
||||
else:
|
||||
image = torch.from_numpy(np.transpose(hwc_array, (2, 0, 1)).copy())
|
||||
|
||||
pixel_values, tiling = processor.preprocess_image(image)
|
||||
|
||||
assert tiling == expected_tiling
|
||||
assert pixel_values.shape == expected_pixel_values.shape
|
||||
assert pixel_values.dtype == torch.bfloat16
|
||||
assert torch.equal(pixel_values, expected_pixel_values)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("image_kind", ["numpy_chw", "torch_chw"])
|
||||
@pytest.mark.parametrize("model_id", [MOONDREAM3_MODEL_ID])
|
||||
def test_processor_apply_accepts_non_pil_image_inputs(
|
||||
image_assets: ImageTestAssets,
|
||||
image_kind: str,
|
||||
model_id: str,
|
||||
):
|
||||
ctx = build_model_context(
|
||||
model_id,
|
||||
limit_mm_per_prompt={"image": 1},
|
||||
)
|
||||
processor = MULTIMODAL_REGISTRY.create_processor(ctx.model_config)
|
||||
|
||||
prompt = "<|endoftext|><image><|md_reserved_0|>query<|md_reserved_1|>What is this?<|md_reserved_2|>" # noqa: E501
|
||||
hwc_array = np.asarray(image_assets[0].pil_image.convert("RGB"))
|
||||
chw_array = np.transpose(hwc_array, (2, 0, 1)).copy()
|
||||
image = chw_array if image_kind == "numpy_chw" else torch.from_numpy(chw_array)
|
||||
|
||||
processed_inputs = processor(
|
||||
prompt,
|
||||
mm_items=processor.info.parse_mm_data({"image": [image]}),
|
||||
hf_processor_mm_kwargs={},
|
||||
)
|
||||
|
||||
image_placeholders = processed_inputs["mm_placeholders"]["image"]
|
||||
assert len(image_placeholders) == 1
|
||||
assert image_placeholders[0].length == EXPECTED_IMAGE_TOKENS
|
||||
|
||||
mm_kwargs = processed_inputs["mm_kwargs"].get_data()
|
||||
assert mm_kwargs["pixel_values"].shape[2:] == (3, 378, 378)
|
||||
|
||||
|
||||
class TestMoondream3TilingLogic:
|
||||
"""CPU-based tests for Moondream3 tiling selection logic.
|
||||
|
||||
These tests validate the select_tiling() function which determines
|
||||
how images are divided into crops for the vision encoder.
|
||||
"""
|
||||
|
||||
def test_small_image_no_tiling(self):
|
||||
"""Small images should use 1x1 tiling."""
|
||||
from vllm.transformers_utils.processors.moondream3 import select_tiling
|
||||
|
||||
tiling = select_tiling(
|
||||
height=300, width=300, crop_size=CROP_SIZE, max_crops=MAX_CROPS
|
||||
)
|
||||
assert tiling == (1, 1)
|
||||
|
||||
def test_exact_crop_size(self):
|
||||
"""Image exactly at crop size should use 1x1."""
|
||||
from vllm.transformers_utils.processors.moondream3 import select_tiling
|
||||
|
||||
tiling = select_tiling(
|
||||
height=CROP_SIZE, width=CROP_SIZE, crop_size=CROP_SIZE, max_crops=MAX_CROPS
|
||||
)
|
||||
assert tiling == (1, 1)
|
||||
|
||||
def test_large_square_image(self):
|
||||
"""Large square image should use multiple tiles."""
|
||||
from vllm.transformers_utils.processors.moondream3 import select_tiling
|
||||
|
||||
tiling = select_tiling(
|
||||
height=800, width=800, crop_size=CROP_SIZE, max_crops=MAX_CROPS
|
||||
)
|
||||
h_tiles, w_tiles = tiling
|
||||
assert h_tiles >= 2
|
||||
assert w_tiles >= 2
|
||||
assert h_tiles * w_tiles <= MAX_CROPS
|
||||
|
||||
def test_wide_image(self):
|
||||
"""Wide image should have more width tiles."""
|
||||
from vllm.transformers_utils.processors.moondream3 import select_tiling
|
||||
|
||||
tiling = select_tiling(
|
||||
height=400, width=1200, crop_size=CROP_SIZE, max_crops=MAX_CROPS
|
||||
)
|
||||
h_tiles, w_tiles = tiling
|
||||
assert w_tiles >= h_tiles
|
||||
|
||||
def test_tall_image(self):
|
||||
"""Tall image should have more height tiles."""
|
||||
from vllm.transformers_utils.processors.moondream3 import select_tiling
|
||||
|
||||
tiling = select_tiling(
|
||||
height=1200, width=400, crop_size=CROP_SIZE, max_crops=MAX_CROPS
|
||||
)
|
||||
h_tiles, w_tiles = tiling
|
||||
assert h_tiles >= w_tiles
|
||||
|
||||
def test_respects_max_crops(self):
|
||||
"""Tiling should not exceed max_crops."""
|
||||
from vllm.transformers_utils.processors.moondream3 import select_tiling
|
||||
|
||||
tiling = select_tiling(
|
||||
height=2000, width=2000, crop_size=CROP_SIZE, max_crops=4
|
||||
)
|
||||
h_tiles, w_tiles = tiling
|
||||
assert h_tiles * w_tiles <= 4
|
||||
|
||||
|
||||
class TestMoondream3VisionShapes:
|
||||
"""CPU-based tests for vision encoder expected shapes.
|
||||
|
||||
These tests verify the mathematical relationships between
|
||||
crop size, patch size, and token counts.
|
||||
"""
|
||||
|
||||
def test_expected_patch_count(self):
|
||||
"""Test 378/14 = 27 patches per side, 729 total."""
|
||||
patches_per_side = CROP_SIZE // PATCH_SIZE
|
||||
total_patches = patches_per_side**2
|
||||
|
||||
assert patches_per_side == 27
|
||||
assert total_patches == EXPECTED_IMAGE_TOKENS - 1
|
||||
|
||||
def test_patch_embedding_input_dim(self):
|
||||
"""Test patch embedding input dimension."""
|
||||
channels = 3
|
||||
input_dim = PATCH_SIZE * PATCH_SIZE * channels
|
||||
|
||||
assert input_dim == 14 * 14 * 3
|
||||
assert input_dim == 588
|
||||
|
||||
|
||||
class TestMoondream3TauAttention:
|
||||
"""CPU-based tests for tau attention scaling components.
|
||||
|
||||
These tests validate the tau attention formula used in Moondream3:
|
||||
- Token-based: tok_q = tanh(gelu(qkv) @ tau_wq.T)
|
||||
- Position-based: tau_pos = 1 + (sigmoid(alpha * log(pos+1)) - 0.5)
|
||||
"""
|
||||
|
||||
def test_tau_position_range(self):
|
||||
"""Test tau position scaling produces values in valid range."""
|
||||
num_heads = 32
|
||||
seq_len = 100
|
||||
|
||||
tau_alpha = torch.randn(num_heads)
|
||||
positions = torch.arange(seq_len)
|
||||
|
||||
pos_float = (positions.float() + 1.0).clamp(min=1e-6)
|
||||
pos_log = pos_float.log()
|
||||
tau_pos = 1.0 + (torch.sigmoid(tau_alpha[:, None] * pos_log[None, :]) - 0.5)
|
||||
|
||||
assert tau_pos.shape == (num_heads, seq_len)
|
||||
# tau_pos should be between 0.5 and 1.5
|
||||
assert tau_pos.min() >= 0.5
|
||||
assert tau_pos.max() <= 1.5
|
||||
|
||||
def test_tau_token_output_range(self):
|
||||
"""Test tau token scaling output is bounded by tanh."""
|
||||
import torch.nn.functional as F
|
||||
|
||||
seq_len = 100
|
||||
qkv_dim = 6144 # 2048 * 3
|
||||
num_heads = 32
|
||||
|
||||
qkv = torch.randn(seq_len, qkv_dim)
|
||||
tau_wq = torch.randn(num_heads, qkv_dim)
|
||||
|
||||
tok_feat = F.gelu(qkv)
|
||||
tok_q = torch.tanh(tok_feat @ tau_wq.t())
|
||||
|
||||
assert tok_q.shape == (seq_len, num_heads)
|
||||
# tanh output is bounded by [-1, 1]
|
||||
assert tok_q.min() >= -1.0
|
||||
assert tok_q.max() <= 1.0
|
||||
@@ -1122,6 +1122,16 @@ _MULTIMODAL_EXAMPLE_MODELS = {
|
||||
extras={"olmo": "allenai/Molmo-7B-O-0924"},
|
||||
trust_remote_code=True,
|
||||
),
|
||||
"Moondream3ForCausalLM": _HfExamplesInfo(
|
||||
"moondream/moondream3-preview",
|
||||
tokenizer="moondream/starmie-v1",
|
||||
trust_remote_code=True,
|
||||
),
|
||||
"HfMoondream": _HfExamplesInfo(
|
||||
"moondream/moondream3-preview",
|
||||
tokenizer="moondream/starmie-v1",
|
||||
trust_remote_code=True,
|
||||
),
|
||||
"Molmo2ForConditionalGeneration": _HfExamplesInfo(
|
||||
"allenai/Molmo2-8B",
|
||||
extras={"olmo": "allenai/Molmo2-O-7B"},
|
||||
|
||||
@@ -523,6 +523,17 @@ def dummy_hf_overrides(
|
||||
|
||||
text_config.update(update_dict)
|
||||
|
||||
# Update n_layers and moe configs for Moondream3 model
|
||||
if model_arch in ("Moondream3ForCausalLM", "HfMoondream"):
|
||||
text_config.update(
|
||||
{
|
||||
"n_layers": num_hidden_layers,
|
||||
"moe_num_experts": num_experts,
|
||||
"moe_experts_per_token": 2,
|
||||
"moe_start_layer": num_hidden_layers,
|
||||
}
|
||||
)
|
||||
|
||||
if hasattr(hf_config, "vision_config"):
|
||||
hf_config.vision_config.update(
|
||||
{
|
||||
@@ -531,6 +542,9 @@ def dummy_hf_overrides(
|
||||
}
|
||||
)
|
||||
|
||||
if model_arch in ("Moondream3ForCausalLM", "HfMoondream"):
|
||||
hf_config.vision_config.update({"enc_n_layers": 1})
|
||||
|
||||
# e.g.: ibm-granite/granite-speech-3.3-2b
|
||||
if hasattr(hf_config, "encoder_config"):
|
||||
hf_config.encoder_config.update(
|
||||
|
||||
Reference in New Issue
Block a user