| import ast |
| import io |
| import os |
| from copy import deepcopy |
| from dataclasses import dataclass |
| from typing import Any, Callable, Dict, List, Optional, Set, Union |
|
|
| import cv2 |
| import numpy as np |
| import pyarrow.parquet as pq |
| import torch |
| from arpeggio import Chord, DataloaderArgs, create_dataloader, register_transform |
| from arpeggio.chord import Chord |
| from arpeggio.tuners import Qwen3VLTransform |
| from arpeggio.utils.conversation_utils import ( |
| chatml_input_ids_to_labels, |
| handle_message_extra_fields, |
| sharegpt_to_hf_format, |
| ) |
| from arpeggio.utils.qwen_vl_utils import get_mrope_index_qwen3_vl |
| from decord import VideoReader, cpu |
| from PIL import Image |
| from qwen_vl_utils import fetch_image, fetch_video, process_vision_info |
| from qwen_vl_utils.vision_process import smart_resize |
| from torchvision import transforms |
| from torchvision.transforms import InterpolationMode |
| from transformers import AutoTokenizer |
|
|
|
|
| DISABLE_CV2_PATCH = os.getenv("DISABLE_CV2_PATCH", "0") == "1" |
|
|
| |
| |
|
|
| _original_pil_resize = Image.Image.resize |
|
|
| _PIL_TO_CV2_INTERP = { |
| Image.Resampling.NEAREST: cv2.INTER_NEAREST, |
| Image.Resampling.BILINEAR: cv2.INTER_LINEAR, |
| Image.Resampling.BICUBIC: cv2.INTER_CUBIC, |
| Image.Resampling.LANCZOS: cv2.INTER_LANCZOS4, |
| |
| 0: cv2.INTER_NEAREST, |
| 2: cv2.INTER_LINEAR, |
| 3: cv2.INTER_CUBIC, |
| 1: cv2.INTER_LANCZOS4, |
| } |
|
|
|
|
| def _cv2_resize(self, size, resample=None, box=None, reducing_gap=None): |
| """OpenCV-accelerated PIL Image.resize().""" |
| |
| if box is not None: |
| return _original_pil_resize(self, size, resample=resample, box=box, reducing_gap=reducing_gap) |
|
|
| if resample is None: |
| resample = Image.Resampling.BICUBIC |
| cv2_interp = _PIL_TO_CV2_INTERP.get(resample, cv2.INTER_LINEAR) |
|
|
| target_w, target_h = size |
| |
| if target_w < self.width or target_h < self.height: |
| cv2_interp = cv2.INTER_AREA |
|
|
| img_array = np.asarray(self) |
| resized = cv2.resize(img_array, (target_w, target_h), interpolation=cv2_interp) |
| return Image.fromarray(resized) |
|
|
|
|
| def enable_cv2_resize(): |
| """Enable OpenCV-accelerated resize.""" |
| Image.Image.resize = _cv2_resize |
|
|
|
|
| def disable_cv2_resize(): |
| """Restore original PIL resize.""" |
| Image.Image.resize = _original_pil_resize |
|
|
|
|
| |
| if not DISABLE_CV2_PATCH: |
| enable_cv2_resize() |
|
|
|
|
| @dataclass |
| class VideoData: |
| """Processed video data with metadata.""" |
|
|
| video: Union[torch.Tensor, List[Image.Image]] |
| metadata: dict |
| sample_fps: float |
|
|
|
|
| class ThothVLTransform(Qwen3VLTransform): |
| """Qwen3-VL transform that supports Thoth/msswift-style data formats. |
| |
| Supports: |
| - content_split: pretrain text data |
| - caption: image captioning data |
| - conversations/messages: multi-turn dialogue |
| - Various image formats: bytes, path, dict, PIL.Image |
| - Various video formats: frames, video bytes, gif |
| - Nested conversations |
| """ |
|
|
| |
|
|
| def _read_image( |
| self, |
| image: Union[bytes, str, Image.Image, dict, None], |
| to_pil: bool = False, |
| ) -> Optional[Image.Image]: |
| """Convert various image formats to PIL Image.""" |
| if image is None: |
| return None |
|
|
| if isinstance(image, Image.Image): |
| return image |
|
|
| if isinstance(image, bytes): |
| return Image.open(io.BytesIO(image)) |
|
|
| if isinstance(image, str): |
| |
| return image |
|
|
| if isinstance(image, dict): |
| if image.get("bytes") is not None: |
| img_bytes = image["bytes"] |
| if isinstance(img_bytes, Image.Image): |
| return img_bytes |
| return Image.open(io.BytesIO(img_bytes)) |
| elif image.get("path") is not None: |
| return image["path"] |
| return None |
|
|
| if isinstance(image, (np.float64, np.float32)): |
| return None |
|
|
| raise ValueError(f"Unsupported image type: {type(image)}") |
|
|
| def _process_images(self, item: dict) -> Optional[List]: |
| """Extract and process images from item.""" |
| raw_images = None |
|
|
| if "jpg" in item: |
| raw_images = [item.pop("jpg")] |
| elif "image" in item: |
| image_data = item.pop("image") |
| if image_data is not None and not isinstance(image_data, (np.float64, np.float32)): |
| raw_images = [image_data] |
| elif "images" in item: |
| raw_images = item.pop("images") |
| if isinstance(raw_images, np.ndarray): |
| raw_images = raw_images.tolist() |
| elif isinstance(raw_images, dict): |
| raw_images = [raw_images] |
|
|
| if not raw_images: |
| return None |
|
|
| images = [] |
| for raw in raw_images: |
| img = self._read_image(raw, to_pil=True) |
| if img is None: |
| continue |
|
|
| if isinstance(img, str): |
| |
| ele = {"type": "image", "image": img} |
| self._patch_visual_element(ele) |
| img = fetch_image(ele, image_patch_size=self._patch_size) |
|
|
| images.append(img) |
|
|
| return images if images else None |
|
|
| |
|
|
| def _read_gif(self, gif_bytes: bytes) -> List[Image.Image]: |
| """Extract frames from a GIF.""" |
| if not isinstance(gif_bytes, bytes): |
| raise TypeError(f"Unsupported gif type: {type(gif_bytes)}") |
|
|
| frames = [] |
| with io.BytesIO(gif_bytes) as byte_stream: |
| with Image.open(byte_stream) as img: |
| try: |
| while True: |
| frames.append(img.copy()) |
| img.seek(img.tell() + 1) |
| except EOFError: |
| pass |
| return frames |
|
|
| def _decode_video_bytes(self, video_bytes: bytes) -> tuple[torch.Tensor, dict, float]: |
| """Decode video from bytes using decord. |
| |
| Returns (video_tensor, metadata, sample_fps) |
| """ |
| vr = VideoReader(io.BytesIO(video_bytes), ctx=cpu(0), num_threads=1) |
|
|
| total_frames = len(vr) |
| fps = vr.get_avg_fps() |
|
|
| max_num_frames = self._video_ele_kwargs.get("max_frames") or int(os.environ.get("FPS_MAX_FRAMES", 32)) |
|
|
| if total_frames <= max_num_frames: |
| indices = list(range(total_frames)) |
| else: |
| indices = np.linspace(0, total_frames - 1, max_num_frames, dtype=int).tolist() |
|
|
| |
| frames = vr.get_batch(indices).asnumpy() |
|
|
| |
| video_tensor = torch.from_numpy(frames).permute(0, 3, 1, 2) |
|
|
| sample_fps = len(indices) / total_frames * fps if total_frames > 0 else 1.0 |
|
|
| metadata = { |
| "fps": fps, |
| "total_num_frames": total_frames, |
| "frames_indices": torch.tensor(indices), |
| } |
|
|
| return video_tensor, metadata, sample_fps |
|
|
| def _process_videos(self, item: dict) -> Optional[List[VideoData]]: |
| """Extract and process videos from item. |
| |
| Returns a list of VideoData, each containing video tensor/frames and metadata. |
| |
| Supported formats: |
| - frames: List[bytes] - Each bytes is an image (frame) |
| - video: bytes - Raw mp4 video bytes |
| - video: str - Video file path |
| - gif: bytes - GIF animation bytes |
| - videos: List[...] - Multiple videos in various formats |
| """ |
| max_num_frames = int(os.environ.get("FPS_MAX_FRAMES", 16)) |
| raw_videos = None |
|
|
| if "frames" in item: |
| raw_frames = item.pop("frames") |
| frames = [] |
| for frame in raw_frames: |
| img = self._read_image(frame) |
| if img is not None and isinstance(img, Image.Image): |
| frames.append(img) |
|
|
| if len(frames) > max_num_frames: |
| indices = np.linspace(0, len(frames) - 1, max_num_frames, dtype=int) |
| frames = [frames[i] for i in indices] |
|
|
| if frames: |
| raw_videos = [frames] |
| elif "video" in item: |
| raw_videos = [item.pop("video")] |
| elif "gif" in item: |
| raw_videos = [self._read_gif(item.pop("gif"))] |
| elif "videos" in item: |
| raw_videos = item.pop("videos") |
| if isinstance(raw_videos, np.ndarray): |
| raw_videos = raw_videos.tolist() |
| if raw_videos and isinstance(raw_videos[0], np.ndarray): |
| raw_videos = [v.tolist() for v in raw_videos] |
|
|
| if not raw_videos: |
| return None |
|
|
| results = [] |
|
|
| try: |
| for raw in raw_videos: |
| if isinstance(raw, list) and raw and isinstance(raw[0], Image.Image): |
| |
| num_frames = len(raw) |
| metadata = { |
| "fps": 1.0, |
| "total_num_frames": num_frames, |
| "frames_indices": torch.arange(num_frames), |
| } |
| results.append(VideoData(video=raw, metadata=metadata, sample_fps=1.0)) |
|
|
| elif isinstance(raw, list) and raw and isinstance(raw[0], bytes): |
| total_frames = len(raw) |
|
|
| if total_frames > max_num_frames: |
| indices = np.linspace(0, total_frames - 1, max_num_frames, dtype=int) |
| else: |
| indices = range(total_frames) |
|
|
| frames = [] |
| for i in indices: |
| img = self._read_image(raw[i]) |
| if img is not None and isinstance(img, Image.Image): |
| frames.append(img) |
|
|
| if frames: |
| num_frames = len(frames) |
| metadata = { |
| "fps": 1.0, |
| "total_num_frames": total_frames, |
| "frames_indices": torch.tensor( |
| list(indices) if total_frames > max_num_frames else list(range(num_frames)) |
| ), |
| } |
| results.append(VideoData(video=frames, metadata=metadata, sample_fps=1.0)) |
|
|
| elif isinstance(raw, bytes): |
| |
| video_tensor, metadata, sample_fps = self._decode_video_bytes(raw) |
| results.append(VideoData(video=video_tensor, metadata=metadata, sample_fps=sample_fps)) |
|
|
| elif isinstance(raw, str): |
| |
| ele = {"type": "video", "video": raw} |
| self._patch_visual_element(ele) |
| result, sample_fps = fetch_video( |
| ele, |
| image_patch_size=self._patch_size, |
| return_video_sample_fps=True, |
| return_video_metadata=True, |
| ) |
|
|
| if isinstance(result, tuple): |
| video_tensor, metadata = result |
| else: |
| video_tensor = result |
| num_frames = video_tensor.shape[0] |
| metadata = { |
| "fps": sample_fps, |
| "total_num_frames": num_frames, |
| "frames_indices": torch.arange(num_frames), |
| } |
| results.append(VideoData(video=video_tensor, metadata=metadata, sample_fps=sample_fps)) |
|
|
| elif isinstance(raw, torch.Tensor): |
| num_frames = raw.shape[0] |
| metadata = { |
| "fps": 1.0, |
| "total_num_frames": num_frames, |
| "frames_indices": torch.arange(num_frames), |
| } |
| results.append(VideoData(video=raw, metadata=metadata, sample_fps=1.0)) |
| except Exception as e: |
| print(f"_process_videos error: {e}") |
| raise e |
|
|
| return results if results else None |
|
|
| |
|
|
| def _normalize_message_format(self, messages: List[Dict]) -> List[Dict]: |
| """Convert from/value format to role/content format and filter system messages. |
| |
| Handles: |
| - from: human/user -> role: user |
| - from: gpt/assistant -> role: assistant |
| - from: system -> filtered out |
| - value -> content |
| - Dirty data fix: if assistant message contains <image>/<video>, swap roles |
| """ |
| if isinstance(messages, np.ndarray): |
| messages = messages.tolist() |
| elif isinstance(messages, str): |
| messages = ast.literal_eval(messages) |
|
|
| normalized = [] |
| for msg in messages: |
| |
| if msg.get("from") == "system" or msg.get("role") == "system": |
| continue |
|
|
| new_msg = {} |
|
|
| |
| if "role" in msg: |
| new_msg["role"] = msg["role"] |
| elif "from" in msg: |
| from_value = msg["from"] |
| if from_value in ("human", "user"): |
| new_msg["role"] = "user" |
| elif from_value in ("gpt", "assistant"): |
| new_msg["role"] = "assistant" |
| else: |
| new_msg["role"] = from_value |
|
|
| |
| if "content" in msg: |
| new_msg["content"] = msg["content"] |
| elif "value" in msg: |
| new_msg["content"] = msg["value"] |
|
|
| normalized.append(new_msg) |
|
|
| |
| normalized = self._fix_misplaced_roles(normalized) |
|
|
| return normalized |
|
|
| def _fix_misplaced_roles(self, messages: List[Dict]) -> List[Dict]: |
| """Fix dirty data where assistant messages contain <image>/<video>. |
| |
| Detection pattern: |
| - First message is from assistant AND contains <image>/<video> |
| - Messages alternate between roles |
| |
| Fix: Swap all user <-> assistant roles |
| """ |
| if not messages: |
| return messages |
|
|
| def _contains_media(content) -> bool: |
| if not isinstance(content, str): |
| return False |
| return "<image>" in content or "<video>" in content |
|
|
| |
| first_msg = messages[0] |
| first_role = first_msg.get("role", "") |
| first_content = first_msg.get("content", "") |
|
|
| |
| if first_role != "assistant" or not _contains_media(first_content): |
| return messages |
|
|
| |
| |
| if len(messages) >= 2: |
| second_role = messages[1].get("role", "") |
| |
| |
| if second_role != "user": |
| |
| return messages |
|
|
| |
| role_map = {"user": "assistant", "assistant": "user"} |
| fixed = [] |
| for msg in messages: |
| new_msg = msg.copy() |
| if new_msg.get("role") in role_map: |
| new_msg["role"] = role_map[new_msg["role"]] |
| fixed.append(new_msg) |
|
|
| return fixed |
|
|
| def _replace_image_with_video_placeholder(self, messages: List[Dict]) -> List[Dict]: |
| """Replace <image> placeholders with <video> when videos are present.""" |
| for msg in messages: |
| if "value" in msg: |
| msg["value"] = msg["value"].replace("<image>", "<video>") |
| elif "content" in msg: |
| msg["content"] = msg["content"].replace("<image>", "<video>") |
| return messages |
|
|
| def _is_nested_conversation(self, messages) -> bool: |
| """Check if messages contain nested conversations.""" |
| if not messages: |
| return False |
| return isinstance(messages[0], (np.ndarray, list)) |
|
|
| |
|
|
| def preprocess_pretrain(self, item: dict) -> Chord: |
| """Process pretrain-style data (content_split).""" |
| item = dict(item) |
|
|
| content = item.pop("content_split") |
| messages = [{"role": "assistant", "content": content}] |
|
|
| |
| images = self._process_images(item) |
|
|
| text = self.processor.apply_chat_template(messages, tokenize=False) |
|
|
| extra_info = item.pop("extra_info", {}) |
| if self.add_raw: |
| extra_info["raw_messages"] = messages |
|
|
| return self._make_model_inputs( |
| text=text, |
| images=images, |
| extra_info=extra_info, |
| do_resize=True, |
| ) |
|
|
| def preprocess_caption(self, item: dict) -> Chord: |
| """Process image captioning data.""" |
| item = dict(item) |
|
|
| caption = item.pop("caption") |
| messages = [ |
| {"role": "user", "content": "<image>"}, |
| {"role": "assistant", "content": caption}, |
| ] |
|
|
| |
| images = self._process_images(item) |
|
|
| |
| prompt = sharegpt_to_hf_format(messages) |
| text = self.processor.apply_chat_template(prompt, tokenize=False) |
|
|
| extra_info = item.pop("extra_info", {}) |
| if self.add_raw: |
| extra_info["raw_messages"] = messages |
|
|
| return self._make_model_inputs( |
| text=text, |
| images=images, |
| extra_info=extra_info, |
| do_resize=True, |
| ) |
|
|
| def preprocess_conversation(self, item: dict) -> Chord: |
| """Process conversation/dialogue data.""" |
| item = dict(item) |
|
|
| |
| if "messages" in item: |
| messages = item.pop("messages") |
| elif "conversations" in item: |
| messages = item.pop("conversations") |
| else: |
| raise ValueError("No messages or conversations found in item") |
|
|
| messages = self._normalize_message_format(messages) |
|
|
| |
| images = self._process_images(item) |
| video_data_list = self._process_videos(item) |
|
|
| videos = None |
| video_metadatas = None |
| video_kwargs = {"do_sample_frames": False} |
|
|
| if video_data_list: |
| messages = self._replace_image_with_video_placeholder(messages) |
|
|
| videos = [vd.video for vd in video_data_list] |
| video_metadatas = [vd.metadata for vd in video_data_list] |
| fps_list = [vd.sample_fps for vd in video_data_list] |
| video_kwargs["fps"] = fps_list |
|
|
| |
| prompt = sharegpt_to_hf_format(messages) |
| text = self.processor.apply_chat_template(prompt, tokenize=False) |
|
|
| extra_info = item.pop("extra_info", {}) |
| if self.add_raw: |
| extra_info["raw_messages"] = messages |
|
|
| return self._make_model_inputs( |
| text=text, |
| images=images, |
| videos=videos, |
| video_metadatas=video_metadatas if video_metadatas else None, |
| extra_info=extra_info, |
| do_resize=True, |
| **video_kwargs, |
| ) |
|
|
| def _process_nested_conversations(self, item: dict) -> List[Chord]: |
| """Process nested conversations into a list of Chords.""" |
| base_item = dict(item) |
|
|
| if "messages" in base_item: |
| nested_convs = base_item.pop("messages") |
| else: |
| nested_convs = base_item.pop("conversations") |
|
|
| if isinstance(nested_convs, np.ndarray): |
| nested_convs = nested_convs.tolist() |
|
|
| results = [] |
| for single_conv in nested_convs: |
| if isinstance(single_conv, np.ndarray): |
| single_conv = single_conv.tolist() |
|
|
| single_item = deepcopy(base_item) |
| single_item["messages"] = single_conv |
|
|
| chord = self.preprocess_conversation(single_item) |
| results.append(chord) |
|
|
| return results |
|
|
| def preprocess(self, item: dict) -> Union[Chord, List[Chord]]: |
| """Main preprocessing entry point. |
| |
| Please refer https://code.byted.org/Thoth/ms-swift/blob/dev.gyf.thoth_vl.hdfs_support/swift/llm/dataset/preprocessor/extra.py |
| |
| Handles various data formats from msswift: |
| - content_split: pretrain text data |
| - caption: image captioning data |
| - messages/conversations: multi-turn dialogue (including nested) |
| """ |
| try: |
| item = dict(item) |
|
|
| |
| if "content_split" in item: |
| return self.preprocess_pretrain(item) |
|
|
| |
| if "caption" in item: |
| return self.preprocess_caption(item) |
|
|
| |
| if "conversations" in item or "messages" in item: |
| |
| conv_key = "messages" if "messages" in item else "conversations" |
| conv_data = item[conv_key] |
|
|
| if isinstance(conv_data, np.ndarray): |
| conv_data = conv_data.tolist() |
| elif isinstance(conv_data, str): |
| conv_data = ast.literal_eval(conv_data) |
|
|
| |
| if self._is_nested_conversation(conv_data): |
| item[conv_key] = conv_data |
| return self._process_nested_conversations(item) |
|
|
| return self.preprocess_conversation(item) |
|
|
| |
| if self.prompt_key in item: |
| return super().preprocess_conversation(item) |
| elif self.document_key in item: |
| return super().preprocess_document(item) |
|
|
| raise RuntimeError(f"Sample contained no usable fields: {list(item.keys())}") |
|
|
| except Exception as e: |
| if not self.allow_skip: |
| raise e |
|
|
| if self.should_use_mrope: |
| position_ids = torch.zeros(3, 1, 0, dtype=torch.long) |
| else: |
| position_ids = torch.zeros(1, 0, dtype=torch.long) |
|
|
| return { |
| "input_ids": torch.zeros(1, 0, dtype=torch.long), |
| "position_ids": position_ids, |
| "attention_mask": torch.zeros(1, 0, dtype=torch.long), |
| "labels": torch.zeros(1, 0, dtype=torch.long), |
| "extra_info": [{}], |
| } |
|
|
|
|
| register_transform("thoth_vl", ThothVLTransform) |
|
|