import base64 import io import json import logging import os import traceback import warnings from copy import deepcopy from functools import cached_property from typing import List, Optional import numpy as np import torch from arpeggio import Chord, TransformBase, register_transform from arpeggio.utils.conversation_utils import chatml_input_ids_to_labels from arpeggio.utils.qwen_vl_utils import get_mrope_index, get_mrope_index_qwen3_vl from PIL import Image from qwen_vl_utils import fetch_image, process_vision_info from transformers import AutoConfig, AutoProcessor from transformers.configuration_utils import PretrainedConfig from transformers.processing_utils import ProcessorMixin from transformers.tokenization_utils_base import PreTrainedTokenizerBase DEFAULT_PROMPT_KEY = os.getenv("DEFAULT_PROMPT_KEY", "messages") SYSTEM_PROMPT = ''' You are an assistant that must first decide whether reasoning is necessary before answering. You must always start with a ... tag. If the question requires reasoning, complex analysis, multi-step deduction, calculation, or careful verification, output: I need to think. your reasoning process answer If the question is simple, factual, direct, or does not require reasoning, output: I don't need to think. answer Rules: - Never skip the tag. - Only output when you selected "I need to think." ''' def decode_image_base64(image_base64: str) -> Image.Image: image_buf = base64.b64decode(image_base64) with io.BytesIO(image_buf) as bio: return Image.open(bio).convert("RGB") class TiViLATransform(TransformBase): def __init__( self, processor: ProcessorMixin, model_config: PretrainedConfig, prompt_key: str = DEFAULT_PROMPT_KEY, add_raw_prompt: bool = False, allow_skip: bool = True, image_min_pixels: Optional[int] = None, image_max_pixels: Optional[int] = None, video_min_pixels: Optional[int] = None, video_max_pixels: Optional[int] = 307200, video_min_frames: Optional[int] = None, video_max_frames: Optional[int] = 16, max_seq_len: Optional[int] = None, **unused_kwargs, ): self.processor = processor self.model_config = model_config self.prompt_key = prompt_key self.add_raw_prompt = add_raw_prompt self.allow_skip = allow_skip self.max_seq_len = max_seq_len self.video_max_frames = video_max_frames self._image_ele_kwargs = { "min_pixels": image_min_pixels, "max_pixels": image_max_pixels, } self._video_ele_kwargs = { "min_pixels": video_min_pixels, "max_pixels": video_max_pixels, "min_frames": video_min_frames, "max_frames": video_max_frames, } self._image_ele_kwargs = {k: v for k, v in self._image_ele_kwargs.items() if v is not None} self._video_ele_kwargs = {k: v for k, v in self._video_ele_kwargs.items() if v is not None} @property def tokenizer(self) -> PreTrainedTokenizerBase: return self.processor.tokenizer @cached_property def _patch_size(self) -> int: return self.model_config.vision_config.patch_size @cached_property def _vision_start_id(self) -> int: return self.tokenizer.encode("<|vision_start|>", add_special_tokens=False)[0] @cached_property def _vision_end_id(self) -> int: return self.tokenizer.encode("<|vision_end|>", add_special_tokens=False)[0] @cached_property def _assistant_token_id(self) -> int: return self.tokenizer.encode("assistant", add_special_tokens=False)[0] @cached_property def _bos_token_id(self) -> int: return self.tokenizer.encode("<|im_start|>", add_special_tokens=False)[0] def process_input_ids_to_labels(self, input_ids: List[int]) -> List[int]: # Qwen uses ChatML return chatml_input_ids_to_labels( input_ids=input_ids, assistant_token_id=self._assistant_token_id, bos_token_id=self._bos_token_id, eos_token_id=self.tokenizer.eos_token_id, ) def _input_ids_to_labels_pretrain(self, input_ids: List[int]) -> List[int]: # For stage1&stage2 interleaved data vision_start_id = self._vision_start_id vision_end_id = self._vision_end_id labels = [] in_vision_block = False for i, token_id in enumerate(input_ids): if token_id == vision_start_id: in_vision_block = True labels.append(-100) elif token_id == vision_end_id: labels.append(-100) in_vision_block = False elif in_vision_block: labels.append(-100) else: labels.append(token_id) if labels and labels[0] != -100: labels[0] = -100 return labels def make_model_inputs( self, text: str, images: Optional[List[Image.Image]] = None, videos: Optional[List[torch.Tensor]] = None, video_kwargs: Optional[dict] = None, video_metadatas: Optional[dict] = None, item: Optional[dict] = None, pt_label_func=None, ) -> Chord: if images is not None and len(images) == 0: images = None if videos is not None and len(videos) == 0: videos = video_metadatas = None video_kwargs = {} if video_kwargs is None: video_kwargs = {} # Process with model processor model_inputs = self.processor( text=text, images=images, videos=videos, video_metadata=video_metadatas, do_resize=False, **video_kwargs, ) # Form labels input_ids = model_inputs["input_ids"][0] if pt_label_func is not None: labels = pt_label_func(input_ids) else: labels = self.process_input_ids_to_labels(input_ids) model_inputs["labels"] = [labels] model_inputs = model_inputs.convert_to_tensors("pt") # A bit out of place but seq_len will be used later seq_len = len(input_ids) if "qwen3" in self.model_config.model_type: model_inputs["position_ids"] = get_mrope_index_qwen3_vl( config=self.model_config, input_ids=model_inputs["input_ids"][0], image_grid_thw=model_inputs.get("image_grid_thw"), video_grid_thw=model_inputs.get("video_grid_thw"), )[:, None] # [3, 1, seq_len] else: # Otherwise assume qwen2.5-vl model_inputs["position_ids"] = get_mrope_index( config=self.model_config, input_ids=model_inputs["input_ids"][0], image_grid_thw=model_inputs.get("image_grid_thw"), video_grid_thw=model_inputs.get("video_grid_thw"), second_per_grid_ts=model_inputs.get("second_per_grid_ts"), )[:, None] # [3, 1, seq_len] # Fill stuff into extra_info extra_info = item.pop("extra_info", {}) assert isinstance(extra_info, dict), "extra_info should be a dictionary" extra_info["seq_len"] = seq_len model_inputs["extra_info"] = [extra_info] # Emplace other keys into item for key, value in item.items(): assert key not in model_inputs, ( f"`{key}` conflicts with `model_inputs`. Please rename this field in your dataset." ) model_inputs[key] = [value] return model_inputs def process_conversation(self, item: dict) -> Chord: messages = item.pop(self.prompt_key) if isinstance(messages, str): messages = json.loads(messages) for message in messages: content = message["content"] if isinstance(content, str): content = [{"type": "text", "text": content}] for i, part in enumerate(content): part_type = part["type"] if part_type == "text": text = part["text"] # add choose logic if message.get("role") == "assistant": if "" in text: text = "I need to think.\n" + text else: text = "I don't need to think.\n" + text content[i] = {"type": "text", "text": text} elif part_type == "image": # TODO: Decode this to PIL Image img = decode_image_base64(part["image"]) content[i] = { "type": "image", "image": img, **self._image_ele_kwargs, } elif part_type == "video": frames = [decode_image_base64(b) for b in part["video"]] # Down sample frames if necessary sample_fps = 1.0 if len(frames) > self.video_max_frames: sample_idxs = np.linspace( 0, len(frames) - 1, self.video_max_frames, dtype=int, ).tolist() sample_fps = len(sample_idxs) / len(frames) frames = [frames[i] for i in sample_idxs] content[i] = { "type": "video", "video": frames, "sample_fps": sample_fps, **self._video_ele_kwargs, } else: raise NotImplementedError(f"invalid part_type={part_type}") # messages = [{"role": "system", "content": SYSTEM_PROMPT}] + messages text = self.processor.apply_chat_template(messages, tokenize=False) images, videos, video_kwargs = process_vision_info( messages, image_patch_size=self._patch_size, return_video_kwargs=True, return_video_metadata=True, ) if videos: videos, video_metadatas = zip(*videos) videos, video_metadatas = list(videos), list(video_metadatas) else: videos = video_metadatas = None # In some cases, extra_info is stored as a list extra_info = item["extra_info"] if isinstance(extra_info, list): item["extra_info"] = extra_info[0] return self.make_model_inputs( text=text, images=images, videos=videos, video_kwargs=video_kwargs, video_metadatas=video_metadatas, item=item, ) def process_interleaved(self, item: dict) -> Chord: text_list = item.pop("texts") image_list = item.pop("images") assert len(text_list) == len(image_list), "text and image lists are not the same length" text_segments = [] images = [] for text, image_bytes in zip(text_list, image_list): if text is not None: text_segments.append(text) if image_bytes is not None and image_bytes != b"\x00": img = Image.open(io.BytesIO(image_bytes)) width, height = img.size ratio = max(width / height, height / width) if ratio > 6: continue img = img.convert("RGB") image_ele = {"type": "image", "image": img, **self._image_ele_kwargs} img = fetch_image(image_ele, image_patch_size=self._patch_size) images.append(img) ("data:image/jpeg;base64,{BASE64_IMAGE}",) text_segments.append("<|vision_start|><|image_pad|><|vision_end|>") text = "".join(text_segments) text = "<|im_start|>" + text + "<|im_end|>" return self.make_model_inputs( text=text, images=images, item=item, pt_label_func=self._input_ids_to_labels_pretrain, ) def make_dummy_sample(self) -> Chord: # This is mainly used in map-style datasets to patch attention backward return { "input_ids": torch.zeros(1, 1, dtype=torch.long), "position_ids": torch.zeros(3, 1, 1, dtype=torch.long), # Assume MRoPE "attention_mask": torch.ones(1, 1, dtype=torch.long), "labels": torch.zeros(1, 1, dtype=torch.long) - 100, "extra_info": [ { "file_name": "skip/skip", "dataset_name": "skip", "seq_len": 1, } ], } def _preprocess(self, item: dict) -> Chord: item = deepcopy(item) if self.prompt_key in item: sample = self.process_conversation(item) else: sample = self.process_interleaved(item) if self.max_seq_len is not None: seq_len = sample["input_ids"].size(-1) if seq_len > self.max_seq_len: extra_info = sample["extra_info"][0] msg = f"Found sample of length {seq_len} extra_info={extra_info}" warnings.warn(msg, UserWarning) sample = self.make_dummy_sample() return sample def preprocess(self, item: dict) -> Chord: try: return self._preprocess(item) except Exception as e: if not self.allow_skip: raise e err_trace = traceback.format_exc() logging.warning(f"Skipped sample due to {e}: {err_trace}") return { "input_ids": torch.zeros(1, 0, dtype=torch.long), "position_ids": torch.zeros(3, 1, 0, dtype=torch.long), "attention_mask": torch.zeros(1, 0, dtype=torch.long), "labels": torch.zeros(1, 0, dtype=torch.long), "extra_info": [{}], } @classmethod def from_pretrained(cls, pretrained_path, **kwargs): processor = AutoProcessor.from_pretrained(pretrained_path) config = AutoConfig.from_pretrained(pretrained_path) return cls(processor=processor, model_config=config, **kwargs) def save_pretrained(self, pretrained_path: str): self.processor.save_pretrained(pretrained_path) self.model_config.save_pretrained(pretrained_path) register_transform("tivila", TiViLATransform)