Files
FreeToken/tests/engine/test_mm_repeated_image.py
Xiaoze Fan 08d728d5e3 feat(mm): serve image input on the Qwen families (#454)
* feat(mm): serve image input on the Qwen VL families

- frontend: OpenAI image_url, Anthropic image blocks and Responses
  input_image (http(s), base64, gated file://) become MMItems in the
  tokenizer workers; image spans carry content pseudo ids so the radix
  cache keys them by content; mrope positions are precomputed per request
- registry: EncoderSpec per family (Qwen3-VL, Qwen3.6, Qwen3.8-Flash-Next
  register a vision encoder serving image) and ModelSpec.mm_processor;
  EngineConfig.active_encoders decides what a process builds,
  served_modalities what it accepts; --text-model-only, --mm-disable,
  --mm-encoder-weights, --mm-embed-cache-device, --mm-max-pixels
- engine and scheduler: per-request encoder-cache row ownership, chunk
  planning on the batch (jobs, gather rows, scatter rows), items encoded
  right before the LM forward and gathered into batch.mm_embeds
- models: the Qwen VL vision tower on the text tower's TP layers with
  DeepStack, block weights streamed from pinned host banks by default,
  merger outputs parked on the host between blocks; SupportsMultimodal
  (encode, place_encoder_weights) and a shared embed_input_ids
- server: image inputs rejected with a client-facing reason when no
  vision encoder is served; GET /v1/stats reports model.input_modalities

* feat(mm): replace the pixel cap with a token budget and processor kwargs

- --image-min-tokens / --image-max-tokens replace --mm-max-pixels; MMProcessor.get_mm_processor_kwargs turns the MultimodalConfig into the processor call's arguments, the default passes mm.processor_kwargs through and Qwen VL converts the budget to pixel areas in size.shortest_edge / longest_edge
- --mm-processor-kwargs hands a JSON object to the checkpoint's image processor call, applied after the token budget
- MMProcessor is an ABC that owns the model path, the config and the lazily loaded image processor; get_mm_processor returns None when --mm-disable leaves no encoder to serve
- the frontend tokenizer, the tokenizer worker and the offline LLM build one processor each and hand it to TokenizeManager, so the tokenize message carries no per-request pixel cap
2026-09-13 15:39:33 -07:00

49 lines
2.2 KiB
Python

"""A request that carries the same image twice, chunked between the two occurrences (a real checkpoint)."""
from __future__ import annotations
import os
import subprocess
import sys
import pytest
CHECKPOINT = os.environ.get("FREETOKEN_QWEN3VL_MODEL", "")
pytestmark = [
pytest.mark.slow,
pytest.mark.skipif(not os.path.exists(os.path.join(CHECKPOINT, "config.json")), reason="FREETOKEN_QWEN3VL_MODEL not set"),
]
# the engine wants a fresh CUDA context, so each run gets its own process
_SCRIPT = """
import io, sys, torch
from PIL import Image
from freetoken.core import SamplingParams
from freetoken.llm import LLM
from freetoken.mm.config import MultimodalConfig
checkpoint, storage = sys.argv[1], sys.argv[2]
llm = LLM(model_path=checkpoint, dtype=torch.bfloat16, attention_backend="auto", max_running_req=1, cuda_graph_max_bs=1,
max_extend_tokens=128, max_seq_len_override=4096, mm=MultimodalConfig(embed_cache_device=storage))
messages = [{"role": "user", "content": [{"type": "image"}, {"type": "image"},
{"type": "text", "text": "What color are these two images? Answer in one word."}]}]
prompt = llm.tokenizer.apply_chat_template(messages, add_generation_prompt=True, tokenize=False)
ids = llm.tokenizer.encode(prompt, add_special_tokens=False)
buf = io.BytesIO(); Image.new("RGB", (256, 256), (255, 0, 0)).save(buf, format="PNG"); red = buf.getvalue()
text = llm.generate([ids], SamplingParams(max_tokens=8, temperature=0.0), images=[[red, red]])[0]["text"]
print("RESULT", repr(text), llm.engine.encoder_cache.stats())
"""
@pytest.mark.parametrize("storage", ["cpu", "cuda"])
def test_repeated_image_survives_the_chunk_boundary(storage):
run = subprocess.run(
[sys.executable, "-c", _SCRIPT, CHECKPOINT, storage],
capture_output=True, text=True, timeout=900, env={**os.environ, "PYTHONPATH": os.environ.get("PYTHONPATH", "")},
)
assert run.returncode == 0, run.stderr[-2000:]
result = [line for line in run.stdout.splitlines() if line.startswith("RESULT")][-1]
assert "red" in result.lower(), result
assert result.endswith("(0, 0)"), result # every claim gathered, nothing left behind