"""processing_qwen4.py -- Qwen4 multimodal processor (no Jinja). ``transformers``' :class:`~transformers.ProcessorMixin.apply_chat_template` renders the prompt through the processor's **Jinja** ``chat_template``. Qwen4, however, renders chat structure in pure Python via :meth:`Qwen4Tokenizer.apply_chat_template` (see ``encoding_qwen4.py``), and ships no Jinja template. Loading the stock ``Qwen3VLProcessor`` therefore fails to read images: with no ``chat_template`` the processor cannot turn a conversation into a prompt at all. This module supplies :class:`Qwen4VLProcessor`. It subclasses ``ProcessorMixin`` directly -- **not** ``Qwen3VLProcessor`` -- so the checkpoint's processing code is self-contained and its behavior is pinned: it does not shift when the installed transformers changes ``Qwen3VLProcessor``'s internals (e.g. the video expansion, which differs across versions). The multimodal glue Qwen4 needs (``__init__`` token setup, ``replace_image_token`` / ``replace_video_token`` and the video timestamp helper) is vendored below, adapted from transformers' ``Qwen3VLProcessor`` and matching its behavior at the time of writing. ``apply_chat_template`` is hand-written to reuse the tokenizer's Python renderer instead of Jinja. The token stream always comes from the tokenizer's own segment-based tokenization (preserving its anti-injection guarantee) -- never from re-tokenizing a flat, expanded string. Pad expansion lives in :meth:`Qwen4VLProcessor.__call__`, together with the pixel features it is derived from: the single placeholder pad each visual emits becomes the real number of vision tokens **in token space**, the count coming from ``grid_thw``. ``apply_chat_template(tokenize=True)`` therefore returns unexpanded, tokenizer-identical ids unless ``return_dict=True`` asks for the features too. The division of labour mirrors the documented Qwen4 XML contract (see ``README.md``): * The encoder renders **one** placeholder pad per visual part, wrapped in the vision delimiters -- ``<|vision_start|><|image_pad|><|vision_end|>`` for an image, ``<|vision_start|><|video_pad|><|vision_end|>`` for a video. This is byte-for-byte what the official Qwen3-VL ``chat_template.jinja`` emits. * Each pad is expanded via the vendored replacers: an image's single ``<|image_pad|>`` becomes ``N`` pads (``N = grid_thw.prod() // merge_size**2``); a video's ``<|video_pad|>`` becomes the per-frame ``<|vision_start|>...<|vision_end|>`` timestamp form. The replacement strings come from ``_process_images`` / ``_process_videos``; only the *splicing* is done in token space instead of on a string, to keep content anti-injection. """ from __future__ import annotations from typing import TYPE_CHECKING, Any from transformers.feature_extraction_utils import BatchFeature from transformers.image_utils import ImageInput, make_flat_list_of_images from transformers.processing_utils import ProcessingKwargs, ProcessorMixin, Unpack from transformers.utils import logging from transformers.video_utils import VideoInput, make_batched_videos from .encoding_qwen4 import Qwen4ChatEncoder if TYPE_CHECKING: # ``encoding_qwen4`` is listed here only so that HF's remote-code loader copies it into the # dynamic-module cache. Keep it even though it is unused. from .encoding_qwen4 import Qwen4ChatEncoder # noqa: F401 from .tokenization_qwen4 import Qwen4Tokenizer logger = logging.get_logger(__name__) # apply_chat_template kwargs consumed by the tokenizer's Python renderer # (encoding_qwen4). Everything else in **kwargs is forwarded to __call__ as # image/video preprocessing options. _TEMPLATE_KEYS = ( "enable_thinking", "reasoning_effort", "preserve_thinking", ) # content-part keys that carry the actual image / video reference, in the same # priority order transformers' base apply_chat_template uses when harvesting # visuals from a conversation. _IMAGE_KEYS = ("image", "url", "path", "base64") _VIDEO_KEYS = ("video", "url", "path") class Qwen4VLProcessorKwargs(ProcessingKwargs, total=False): # Same defaults as transformers' Qwen3VLProcessorKwargs. _defaults = { "text_kwargs": { "padding": False, "return_token_type_ids": False, "return_mm_token_type_ids": True, }, "videos_kwargs": {"return_metadata": True}, } class Qwen4VLProcessor(ProcessorMixin): """Self-contained Qwen4 VL processor whose chat rendering is Python, not Jinja. Subclasses ``ProcessorMixin`` directly so the checkpoint does not depend on (or inherit behavior from) transformers' ``Qwen3VLProcessor`` -- the video expansion in particular is pinned here rather than tracking whatever the installed transformers ships. Sub-processors (image/video/tokenizer) are still resolved by ``AutoProcessor`` from the checkpoint's configs. """ valid_processor_kwargs = Qwen4VLProcessorKwargs # ================================================================== # multimodal glue -- vendored from transformers Qwen3VLProcessor so the # checkpoint is self-contained and version-pinned. # ================================================================== def __init__( self, image_processor=None, tokenizer=None, video_processor=None, chat_template=None, **kwargs, ): self.image_token = ( "<|image_pad|>" if not hasattr(tokenizer, "image_token") else tokenizer.image_token ) self.video_token = ( "<|video_pad|>" if not hasattr(tokenizer, "video_token") else tokenizer.video_token ) self.image_token_id = ( tokenizer.image_token_id if getattr(tokenizer, "image_token_id", None) else tokenizer.convert_tokens_to_ids(self.image_token) ) self.video_token_id = ( tokenizer.video_token_id if getattr(tokenizer, "video_token_id", None) else tokenizer.convert_tokens_to_ids(self.video_token) ) super().__init__( image_processor, tokenizer, video_processor, chat_template=chat_template ) self.vision_start_token = ( "<|vision_start|>" if not hasattr(tokenizer, "vision_start_token") else tokenizer.vision_start_token ) self.vision_end_token = ( "<|vision_end|>" if not hasattr(tokenizer, "vision_end_token") else tokenizer.vision_end_token ) self.vision_start_token_id = ( tokenizer.vision_start_token_id if getattr(tokenizer, "vision_start_token_id", None) else tokenizer.convert_tokens_to_ids(self.vision_start_token) ) self.vision_end_token_id = ( tokenizer.vision_end_token_id if getattr(tokenizer, "vision_end_token_id", None) else tokenizer.convert_tokens_to_ids(self.vision_end_token) ) def replace_image_token(self, image_inputs: dict, image_idx: int, **kwargs) -> str: merge_length = self.image_processor.merge_size**2 num_image_tokens = ( image_inputs["image_grid_thw"][image_idx].prod() // merge_length ) return self.image_token * num_image_tokens def replace_video_token(self, video_inputs: dict, video_idx: int, **kwargs) -> str: merge_length = self.video_processor.merge_size**2 num_frames = video_inputs["video_grid_thw"][video_idx][0] frame_seqlen = ( video_inputs["video_grid_thw"][video_idx][1:].prod() // merge_length ) metadata = video_inputs["video_metadata"][video_idx] video_placeholder = "" if metadata.fps is None: logger.warning_once( "Qwen3VL requires frame timestamps to construct prompts, but the `fps` of the input video could " "not be inferred. Probably `video_metadata` was missing from inputs and you passed pre-sampled " "frames. Defaulting to `fps=24`. Please provide `video_metadata` for more accurate results." ) metadata.fps = 24 if metadata.fps is None else metadata.fps curr_timestamp = self._calculate_timestamps( metadata.frames_indices, metadata.fps, self.video_processor.temporal_patch_size, ) for frame_idx in range(num_frames): curr_time = curr_timestamp[frame_idx] video_placeholder += f"<{curr_time:.1f} seconds>" video_placeholder += ( self.vision_start_token + self.video_token * frame_seqlen + self.vision_end_token ) return video_placeholder def _calculate_timestamps(self, indices, video_fps: float, merge_size: int = 2): if not isinstance(indices, list): indices = indices.tolist() if len(indices) % merge_size != 0: indices.extend( indices[-1] for _ in range(merge_size - len(indices) % merge_size) ) timestamps = [idx / video_fps for idx in indices] timestamps = [ timestamps[i] if getattr(self.video_processor, "timestamp_anchor", "midpoint") == "start" else (timestamps[i] + timestamps[i + merge_size - 1]) / 2 for i in range(0, len(timestamps), merge_size) ] return timestamps def post_process_image_text_to_text( self, generated_outputs, skip_special_tokens=True, clean_up_tokenization_spaces=False, **kwargs, ): return self.tokenizer.batch_decode( generated_outputs, skip_special_tokens=skip_special_tokens, clean_up_tokenization_spaces=clean_up_tokenization_spaces, **kwargs, ) @property def model_input_names(self): return super().model_input_names + ["mm_token_type_ids"] # ------------------------------------------------------------------ # __call__ (ids-only entry point; handles vision-pad expansion) # ------------------------------------------------------------------ def __call__( self, images: ImageInput | None = None, text: str | list[str] | None = None, videos: VideoInput | None = None, input_ids: list[int] | list[list[int]] | None = None, **kwargs: Unpack[Qwen4VLProcessorKwargs], ) -> BatchFeature: """Build model inputs from pre-tokenized *input_ids* and optional visuals. The safe input is pre-tokenized ``input_ids`` from ``self.apply_chat_template(tokenize=True)`` or, equivalently, ``self.tokenizer.apply_chat_template(tokenize=True)`` -- the two are per-token identical, and both carry **one** placeholder pad per visual. This method processes the images / videos to obtain pixel features **and** the real token count per visual, then expands each single pad in token space. Ids that are already expanded (e.g. the ``input_ids`` of a previous ``BatchFeature``) must not be passed back in; the pad/visual count check below rejects them. ``text`` is accepted only as a **legacy compatibility** path for callers that still hand over a rendered string (e.g. existing sglang / vllm workers that cannot be migrated to ids yet). It is **not** anti-injection safe: re-tokenizing a flat string cannot tell template control tokens from content, so literal special-token strings in user/tool/assistant text are promoted to real control ids (and a literal ``<|image_pad|>`` in content even trips the pad/visual count check). New callers should pass pre-tokenized ``input_ids``; if both are given, ``input_ids`` wins and ``text`` is ignored. Typical usage with ``qwen_vl_utils``:: messages = processor.normalize_messages(messages) token_ids = processor.apply_chat_template( messages, tokenize=True, add_generation_prompt=True, ) # one pad per visual; identical to processor.tokenizer's output images, videos = process_vision_info(messages) inputs = processor( input_ids=token_ids, images=images, videos=videos, do_resize=False, return_tensors="pt", ) """ if input_ids is None: if text is None: raise ValueError( "Qwen4VLProcessor() requires `input_ids` or `text`. Prefer " "pre-tokenized `input_ids` from " "processor.apply_chat_template(messages, tokenize=True)." ) # Legacy compatibility path for callers still passing a rendered # string. Re-tokenizing a flat string drops the segment boundaries # that keep content special-token strings as plain bytes, so this # path does NOT carry the anti-injection guarantee -- warn, loudly # and once, and point at the ids path. logger.warning_once( "Qwen4VLProcessor() was called with `text` (a rendered string). " "This legacy compatibility path re-tokenizes the whole string and " "does NOT preserve the anti-injection guarantee: literal " "special-token strings in user/tool/assistant content are promoted " "to control ids. Pass pre-tokenized `input_ids` from " "processor.apply_chat_template(messages, tokenize=True) for the safe path." ) texts = list(text) if isinstance(text, (list, tuple)) else [text] input_ids = [self.tokenizer.encode(t) for t in texts] elif text is not None: logger.warning_once( "Qwen4VLProcessor() got both `input_ids` and `text`; using " "`input_ids` (the anti-injection path) and ignoring `text`." ) if isinstance(input_ids[0], int): input_ids = [input_ids] return_tensors = kwargs.pop("return_tensors", None) merged = self._merge_kwargs( self.valid_processor_kwargs, tokenizer_init_kwargs=getattr(self.tokenizer, "init_kwargs", {}), **kwargs, ) # Read the text-processing knobs from the merged text_kwargs, so both the # flat form (`padding=True`) and the nested form (`text_kwargs={"padding": # True}`) take effect -- _merge_kwargs routes either into text_kwargs. text_kwargs = merged["text_kwargs"] padding = text_kwargs.get("padding", False) truncation = text_kwargs.get("truncation", False) max_length = text_kwargs.get("max_length", None) # A single PIL image / numpy array has no len(); normalize images and # videos to a flat list (one video array per video) before counting, so a # bare image/video works as well as a list. The empty-list case is left # alone -- the make_* helpers reject it, and it already means "no visual". if images is not None and not ( isinstance(images, (list, tuple)) and len(images) == 0 ): images = make_flat_list_of_images(images) if videos is not None and not ( isinstance(videos, (list, tuple)) and len(videos) == 0 ): videos = make_batched_videos(videos) has_images = images is not None and len(images) > 0 has_videos = videos is not None and len(videos) > 0 processed_images, image_repls = ( self._process_images(images, **merged["images_kwargs"]) if has_images else ({}, []) ) processed_videos, video_repls = ( self._process_videos(videos, **merged["videos_kwargs"]) if has_videos else ({}, []) ) # The i-th pad is expanded with the i-th visual, so the counts must agree # exactly. Too few visuals would raise a bare StopIteration mid-expansion; # too many would silently leave pixel_values / *_grid_thw rows with no pads # pointing at them, desyncing the batch. Fail here, with the numbers. for kind, token_id, repls in ( ("image", self.image_token_id, image_repls), ("video", self.video_token_id, video_repls), ): n_pads = sum(1 for ids in input_ids for t in ids if int(t) == token_id) if n_pads != len(repls): raise ValueError( f"got {len(repls)} {kind}(s) but `input_ids` carry {n_pads} " f"<|{kind}_pad|> placeholder(s); each {kind} must line up with " f"exactly one pad. Pass the visuals of *this* conversation, in " f"reading order, and ids straight from " f"tokenizer.apply_chat_template(tokenize=True) (already-expanded " f"ids must not be re-submitted)." ) # Expand single vision pads to real token counts in token space. image_iter, video_iter = iter(image_repls), iter(video_repls) expanded = [ self._expand_pad_ids(ids, image_iter, video_iter) for ids in input_ids ] if truncation and max_length is not None: kept = [ids[:max_length] for ids in expanded] if (has_images or has_videos) and any( self._vision_pad_count(cut) != self._vision_pad_count(full) for full, cut in zip(expanded, kept) ): raise ValueError( f"truncation=True with max_length={max_length} dropped vision " "placeholder tokens, which would desync input_ids from " "pixel_values / *_grid_thw. Increase max_length, or truncate the " "conversation before adding images/videos." ) expanded = kept padded = self.tokenizer.pad( [{"input_ids": ids, "attention_mask": [1] * len(ids)} for ids in expanded], padding=padding, max_length=max_length if padding else None, return_attention_mask=True, return_tensors=None, ) data: dict[str, Any] = { "input_ids": padded["input_ids"], "attention_mask": padded["attention_mask"], } if merged["text_kwargs"].get("return_mm_token_type_ids", True): data["mm_token_type_ids"] = self.create_mm_token_type_ids(data["input_ids"]) data.update(processed_images) data.update(processed_videos) if not merged["videos_kwargs"].get("return_metadata"): data.pop("video_metadata", None) data = {k: v for k, v in data.items() if k not in self.unused_input_names} return BatchFeature( data, tensor_type=return_tensors, skip_tensor_conversion=self.skip_tensor_conversion, ) # ------------------------------------------------------------------ # chat template (hand-written, Jinja-free) # ------------------------------------------------------------------ def apply_chat_template( self, conversation: list[dict] | list[list[dict]], chat_template: str | None = None, tools: list[dict] | None = None, add_generation_prompt: bool = False, tokenize: bool = False, return_tensors: str | None = None, return_dict: bool = False, processor_kwargs: dict | None = None, **kwargs: Any, ): """Render a conversation with the Qwen4 Python encoder, then process visuals. The token stream always comes from the tokenizer's own segment-based ``apply_chat_template`` -- never from re-tokenizing a flat string -- so the processor inherits its anti-injection guarantee (special-token strings that appear inside user/tool/assistant *content* stay plain bytes, exactly as ``encoding_qwen4`` intends): * ``tokenize=False`` -> the ChatML/XML prompt string (or a list, batched), byte-for-byte equal to ``tokenizer.apply_chat_template(tokenize=False)``. * ``tokenize=True, return_dict=False`` (the default) -> ``input_ids`` **per-token identical to** ``tokenizer.apply_chat_template(tokenize=True)``, i.e. **one placeholder pad per visual, not expanded**, with the tokenizer's own shape and ``return_tensors`` semantics. Pad expansion is inseparable from the pixel features (the count comes from ``grid_thw``), and this path returns ids only -- expanding here would hand back ids that match no ``pixel_values`` the caller holds. The visuals are therefore not even preprocessed. * ``tokenize=True, return_dict=True`` -> visuals are collected from the conversation and passed to ``__call__``, which expands each single vision pad to its real token count and returns the full ``BatchFeature`` (``pixel_values``, ``*_grid_thw``, ``mm_token_type_ids``, ...). Note this deliberately departs from ``ProcessorMixin``, whose ``return_dict=False`` returns the *expanded* ids of ``__call__``: for Qwen4 the tokenizer is the reference for a bare id stream. Qwen4 has no Jinja template, so a Jinja ``chat_template`` is rejected -- whether passed as the argument or loaded from a ``chat_template.jinja`` in the checkpoint into ``self.chat_template`` -- rather than silently ignored. Reasoning knobs (``thinking`` / ``enable_thinking`` / ``reasoning_effort`` / ``preserve_thinking``) are forwarded to the tokenizer; all remaining keyword arguments are image/video preprocessing options. """ tokenizer: "Qwen4Tokenizer" = ( self.tokenizer ) # segment-based, anti-injection renderer # Qwen4 renders in Python; a Jinja template must never silently take over or # be silently ignored. Reject both an explicit `chat_template` argument and a # `chat_template.jinja` loaded from the checkpoint into `self.chat_template`. if chat_template is not None or self.chat_template is not None: raise ValueError( "Qwen4VLProcessor renders chat via the tokenizer's Python encoder and " "does not use a Jinja `chat_template`, but one was provided (the " "`chat_template` argument, or a chat_template.jinja loaded into the " "processor). Remove it -- Qwen4 renders without Jinja." ) if kwargs.pop("continue_final_message", False): raise NotImplementedError( "Qwen4VLProcessor does not support continue_final_message." ) if kwargs.pop("return_assistant_tokens_mask", False): raise NotImplementedError( "return_assistant_tokens_mask is a Jinja-offset feature; use the " "encoder's render_tokens_and_labels for Qwen4 SFT masks." ) template_kwargs = {k: kwargs.pop(k) for k in _TEMPLATE_KEYS if k in kwargs} processor_kwargs = {**kwargs, **(processor_kwargs or {})} is_batched = tokenizer._is_batched_conversation(conversation) conversations = list(conversation) if is_batched else [conversation] if not tokenize: prompts = [ tokenizer.apply_chat_template( messages, tools=tools, tokenize=False, add_generation_prompt=add_generation_prompt, **template_kwargs, ) for messages in conversations ] return prompts if is_batched else prompts[0] # --- tokenize=True, return_dict=False ------------------------------ # Ids only: hand the whole conversation to the tokenizer and return its # output untouched, so this is per-token (and shape-for-shape) identical # to tokenizer.apply_chat_template(tokenize=True) -- one pad per visual. # Expansion belongs with the pixel features it is derived from; see the # docstring. if not return_dict: forwarded = { key: processor_kwargs.pop(key) for key in ("padding", "truncation", "max_length") if key in processor_kwargs } if processor_kwargs: logger.warning_once( "Qwen4VLProcessor.apply_chat_template(tokenize=True, " f"return_dict=False) ignores image/video options ({', '.join(sorted(processor_kwargs))}): " "this path returns ids with one unexpanded pad per visual and " "does not preprocess the visuals. Use return_dict=True to get " "expanded ids plus pixel features." ) return tokenizer.apply_chat_template( conversation, tools=tools, tokenize=True, add_generation_prompt=add_generation_prompt, return_tensors=return_tensors, return_dict=False, **forwarded, **template_kwargs, ) # --- tokenize=True, return_dict=True ------------------------------- # Segment-based ids from the tokenizer (anti-injection; one pad per # visual). This is the *only* tokenization -- we never re-tokenize a # flat string, which is what would promote special-looking content. base_ids = [ tokenizer.apply_chat_template( messages, tools=tools, tokenize=True, add_generation_prompt=add_generation_prompt, **template_kwargs, ) for messages in conversations ] # Collect visuals from the conversation, fetch them, and delegate to # __call__, which handles expansion + pixel features. batch_images, batch_videos = [], [] for messages in conversations: imgs, vids = self._collect_visuals( messages, preserve_thinking=template_kwargs.get("preserve_thinking", True), ) batch_images.append(imgs) batch_videos.append(vids) has_images = any(batch_images) has_videos = any(batch_videos) fetched_images, _, fetched_videos, _ = self.prepare_inputs_layout( images=batch_images if has_images else None, text=None, videos=batch_videos if has_videos else None, ) return self( input_ids=base_ids, images=fetched_images if has_images else None, videos=fetched_videos if has_videos else None, return_tensors=return_tensors, **processor_kwargs, ) def _vision_pad_count(self, ids: list[int]) -> int: """Number of image/video pad tokens in ``ids`` (one per vision token).""" return sum( 1 for t in ids if t == self.image_token_id or t == self.video_token_id ) def _expand_pad_ids(self, ids: list[int], image_repls, video_repls) -> list[int]: """Replace each single vision pad id with its expanded, pre-tokenized run. ``image_repls`` / ``video_repls`` are iterators over the per-visual replacement strings produced by ``_process_images`` / ``_process_videos`` (consumed in reading order). Each is tokenized with ``allow_special=True`` -- correct because the replacements are pure scaffolding (pads, vision delimiters, timestamp markers), never user data. """ out: list[int] = [] for token_id in ids: token_id = int(token_id) if token_id == self.image_token_id: out.extend( self.tokenizer.tokenize_segment( next(image_repls), allow_special=True ) ) elif token_id == self.video_token_id: out.extend( self.tokenizer.tokenize_segment( next(video_repls), allow_special=True ) ) else: out.append(token_id) return out # ------------------------------------------------------------------ # helpers # ------------------------------------------------------------------ def normalize_messages( self, conversation: list[dict], *, preserve_thinking: bool = True, ) -> list[dict]: """Prepare the same message order as the tokenizer for external media readers. Use this view for both tokenization and image/video extraction. Match the tokenizer's preserve_thinking option; caller-owned input is unchanged. """ return Qwen4ChatEncoder(self.tokenizer).normalize_messages( conversation, preserve_thinking=preserve_thinking, ) def _collect_visuals( self, conversation: list[dict], *, preserve_thinking: bool = True, ) -> tuple[list[Any], list[Any]]: """Harvest image and video references from a conversation, in reading order. The order matches the order the encoder emits placeholder pads, so the i-th harvested image lines up with the i-th ``<|image_pad|>`` (same for video) during pad expansion. Both the flat HF shape (``{"type": "image", "url"/"image"/"path"/"base64": ...}``) and OpenAI's nested ``{"type": "image_url", "image_url": {"url": ...}}`` are accepted -- the encoder already renders a pad for either, so the harvester must find both (same for ``video`` / ``video_url``). """ images: list[Any] = [] videos: list[Any] = [] # Filtering and tool-result order must match the tokenizer's message view. for message in self.normalize_messages( conversation, preserve_thinking=preserve_thinking, ): content = message.get("content") if not isinstance(content, list): continue for part in content: if not isinstance(part, dict): continue ptype = part.get("type") if ptype in ("image", "video"): keys = _IMAGE_KEYS if ptype == "image" else _VIDEO_KEYS ref = next((part[k] for k in keys if k in part), None) elif ptype in ("image_url", "video_url"): info = part.get(ptype) # OpenAI: {"url": ...} (or a bare string) ref = info.get("url") if isinstance(info, dict) else info else: continue if ref is not None: (images if ptype in ("image", "image_url") else videos).append(ref) return images, videos __all__ = ["Qwen4VLProcessor"]