Files
FreeToken/python/freetoken/message/backend.py
T
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

98 lines
3.0 KiB
Python

from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Dict, List
import torch
from freetoken.core import SamplingParams
from .utils import deserialize_type, serialize_type
@dataclass
class BaseBackendMsg:
def encoder(self) -> Dict:
return serialize_type(self)
@staticmethod
def decoder(json: Dict) -> BaseBackendMsg:
return deserialize_type(globals(), json)
@dataclass
class BatchBackendMsg(BaseBackendMsg):
data: List[BaseBackendMsg]
@dataclass
class ExitMsg(BaseBackendMsg):
pass
@dataclass
class MMItem:
"""One multimodal input of a request (an image, video or audio clip).
Family extras from the processor live in model_specific_data and read back as attributes (item.grid_thw).
offsets are half-open [start, end) spans in input_ids; an item may occupy several.
Exactly one of feature / precomputed_embeddings is set.
"""
modality: str
hash: int
pad_value: int
offsets: List[List[int]]
feature: torch.Tensor | None = None # raw processor output (CPU), encoded by the engine
precomputed_embeddings: torch.Tensor | None = None # final encoder output, skips encoding
model_specific_data: Dict[str, Any] = field(default_factory=dict)
def __getattr__(self, name: str) -> Any:
data = self.__dict__.get("model_specific_data")
if data is not None and name in data:
return data[name]
raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'")
@property
def num_tokens(self) -> int:
return sum(end - start for start, end in self.offsets)
def is_image(self) -> bool:
return self.modality == "image"
def validate(self) -> None:
if not self.offsets or any(end <= start for start, end in self.offsets):
raise ValueError(f"MMItem offsets must be non-empty half-open spans: {self.offsets}")
if (self.feature is None) == (self.precomputed_embeddings is None):
raise ValueError("MMItem needs exactly one of feature / precomputed_embeddings")
def encoder(self) -> Dict:
return serialize_type(self)
@dataclass
class UserMsg(BaseBackendMsg):
uid: int
input_ids: torch.Tensor # CPU 1D int32 tensor
sampling_params: SamplingParams
# per-image processor outputs, in prompt order
mm_items: List[MMItem] | None = None
# precomputed [3, len(input_ids)] mrope positions and decode delta; None for text-only requests and 1-D rope models
mrope_positions: torch.Tensor | None = None
mrope_delta: int = 0
@dataclass
class AbortBackendMsg(BaseBackendMsg):
uid: int
@dataclass
class CacheRebuildBackendMsg(BaseBackendMsg):
# tokenizer worker -> scheduler: request a runtime KV/MoE/GDN cache resize.
request_id: str
moe_cache_size: int | None = None
num_pages: int | None = None
num_mamba_slots: int | None = None
num_swa_pages: int | None = None
mode: str = "if_idle" # only "if_idle" is supported; "drain" is deferred (rejected)