Files
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

81 lines
3.1 KiB
Python

from __future__ import annotations
from typing import TYPE_CHECKING
import torch
from freetoken.core import get_global_ctx
from freetoken.models.qwen3.model import Qwen3ForCausalLM, Qwen3Model
from freetoken.models.blocks import embed_input_ids
from freetoken.models.qwen3_moe.model import Qwen3MoeForCausalLM, Qwen3Model as Qwen3MoeModel
from .vision import Qwen3VLVisionModel, QwenVLVisionMixin
if TYPE_CHECKING:
from freetoken.models.config import ModelConfig
def deepstack_add(
x: torch.Tensor, rows: torch.Tensor, mm_embeds: torch.Tensor, level: int, hidden_size: int
) -> None:
"""Add DeepStack level `level` (the column block after the main embedding) onto the image rows of x, in place."""
lo = hidden_size * (level + 1)
x.index_add_(0, rows, mm_embeds[:, lo : lo + hidden_size].to(x.dtype))
class Qwen3VLTextModel(Qwen3Model):
def __init__(self, config: ModelConfig):
super().__init__(config)
self._deepstack_levels = len(config.vision_config.deepstack_visual_indexes) if config.vision_config else 0
def forward(self, input_ids: torch.Tensor) -> torch.Tensor:
batch = get_global_ctx().batch
x = embed_input_ids(self.embed_tokens, input_ids, batch)
residual: torch.Tensor | None = None
for level, layer in enumerate(self.layers.op_list):
x, residual = layer.forward(x, residual)
if batch.mm_embeds is not None and level < self._deepstack_levels:
deepstack_add(x, batch.mm_rows, batch.mm_embeds, level, x.shape[1])
return self.norm.forward(x, residual)[0]
class Qwen3VLMoeTextModel(Qwen3MoeModel):
def __init__(self, config: ModelConfig):
super().__init__(config)
self._deepstack_levels = len(config.vision_config.deepstack_visual_indexes) if config.vision_config else 0
def forward(self, input_ids: torch.Tensor) -> torch.Tensor:
batch = get_global_ctx().batch
x = embed_input_ids(self.embed_tokens, input_ids, batch)
residual: torch.Tensor | None = None
for level, layer in enumerate(self.layers.op_list):
x, residual = layer.forward(x, residual)
if batch.mm_embeds is not None and level < self._deepstack_levels:
deepstack_add(x, batch.mm_rows, batch.mm_embeds, level, x.shape[1])
return self.norm.forward(x, residual)[0]
class Qwen3VLForConditionalGeneration(QwenVLVisionMixin, Qwen3ForCausalLM):
model_cls = Qwen3VLTextModel
def __init__(self, config: ModelConfig):
super().__init__(config)
if config.is_multimodal:
self.visual = Qwen3VLVisionModel(config.vision_config, quant_config=config.quant, prefix="visual")
class Qwen3VLMoeForConditionalGeneration(QwenVLVisionMixin, Qwen3MoeForCausalLM):
model_cls = Qwen3VLMoeTextModel
def __init__(self, config: ModelConfig):
super().__init__(config)
if config.is_multimodal:
self.visual = Qwen3VLVisionModel(config.vision_config, quant_config=config.quant, prefix="visual")
__all__ = [
"Qwen3VLForConditionalGeneration",
"Qwen3VLMoeForConditionalGeneration",
"deepstack_add",
]