devboxbackup / playground /Abbie-b200 /trainer_utils /thothvl_transform.py
jasonfan's picture
Add files using upload-large-folder tool
f0d6538 verified
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"
# ==================== OpenCV Resize Monkey Patch ====================
# Patch PIL.Image.resize to use OpenCV
_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,
# Compat with older PIL versions
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()."""
# Fall back to original for box parameter (crop + 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
# Use INTER_AREA for downsampling (better quality)
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
# Enable by default
if not DISABLE_CV2_PATCH:
enable_cv2_resize()
@dataclass
class VideoData:
"""Processed video data with metadata."""
video: Union[torch.Tensor, List[Image.Image]] # video tensor or PIL frames
metadata: dict # contains fps, total_num_frames, frames_indices
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
"""
# ==================== Image Processing ====================
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):
# Path to image - will be handled by fetch_image later
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):
# Path - use fetch_image
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
# ==================== Video Processing ====================
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()
# numpy array: [N, H, W, C]
frames = vr.get_batch(indices).asnumpy()
# [N, C, H, W]
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):
# List of PIL Images (frames)
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 bytes - use decord
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):
# Video file path
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
# ==================== Conversation Processing ====================
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:
# Skip system messages
if msg.get("from") == "system" or msg.get("role") == "system":
continue
new_msg = {}
# Handle role/from
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
# Handle content/value
if "content" in msg:
new_msg["content"] = msg["content"]
elif "value" in msg:
new_msg["content"] = msg["value"]
normalized.append(new_msg)
# Fix dirty data: if assistant message contains <image>/<video>, swap roles
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
# Check first message
first_msg = messages[0]
first_role = first_msg.get("role", "")
first_content = first_msg.get("content", "")
# Only fix if: first message is assistant AND contains media
if first_role != "assistant" or not _contains_media(first_content):
return messages
# Additional validation: check if this looks like a swapped conversation
# (i.e., roles alternate properly, just in wrong order)
if len(messages) >= 2:
second_role = messages[1].get("role", "")
# Expected pattern after fix: user, assistant, user, assistant...
# Current pattern (wrong): assistant, user, assistant, user...
if second_role != "user":
# Doesn't match expected dirty pattern, don't fix
return messages
# Swap all roles
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))
# ==================== Main Preprocessing Methods ====================
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}]
# Process any images
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},
]
# Process images
images = self._process_images(item)
# Convert to HF format for apply_chat_template
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)
# Get messages from either 'messages' or 'conversations' key
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)
# Process images and videos
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
# Convert to HF format
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) # Shallow copy
# Handle content_split (pretrain style)
if "content_split" in item:
return self.preprocess_pretrain(item)
# Handle caption (image captioning style)
if "caption" in item:
return self.preprocess_caption(item)
# Handle conversations/messages
if "conversations" in item or "messages" in item:
# Get the conversation data
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)
# Check for nested conversations
if self._is_nested_conversation(conv_data):
item[conv_key] = conv_data
return self._process_nested_conversations(item)
return self.preprocess_conversation(item)
# Fallback to parent class behavior
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)