code-Psi0-yth-v20 / scripts /data /cache_omni_hidden_states.py
Tinghong-Ye22's picture
Add files using upload-large-folder tool
fe7c37d verified
Raw History Blame Contribute Delete
52.5 kB
from __future__ import annotations import argparse import gc import hashlib import json import math import os import time import traceback import warnings from collections import deque from concurrent.futures import FIRST_COMPLETED, Future, ThreadPoolExecutor, wait from dataclasses import dataclass from pathlib import Path from typing import Any, Iterable, Iterator import numpy as np import torch import torch.distributed as dist from safetensors.torch import save_file from tqdm import tqdm from transformers import AutoConfig, Qwen2_5OmniProcessor, Qwen2_5OmniThinkerForConditionalGeneration from psi.data.seed.seed_audio_motion_dataset import _AUDIO_COMMAND_PROMPT_POOLS from psi.data.seed.seed_video_motion_dataset import _VIDEO_MOTION_PROMPT_POOLS OMNI_DEFAULT_SYSTEM_PROMPT = ( "You are Qwen, a virtual human developed by the Qwen Team, Alibaba Group, " "capable of perceiving auditory and visual inputs, as well as generating text and speech." ) SUPPORTED_TASKS = ( "audio_only", "audio_command_text", "audio_command_only", "video_clip_text", "video_clip_only", ) @dataclass(frozen=True) class SourcePreset: name: str modality: str dataset_root: Path manifest_path: Path allowed_tasks: tuple[str, ...] instruction_key: str = "" audio_path_key: str = "audio_path" video_path_key: str = "video_path" video_embed_dir: Path | None = None is_audio_dir_manifest: bool = False SOURCE_PRESETS: dict[str, SourcePreset] = { "2264_with_audio": SourcePreset( name="2264_with_audio", modality="audio", dataset_root=Path("/cpfs01/thscc/sharestorage/AIGC-06-01/Hithink_VideoGen_Group/user_workspace/buwendong/videogen/2264_with_audio"), manifest_path=Path("/cpfs01/thscc/sharestorage/AIGC-06-01/Hithink_VideoGen_Group/user_workspace/buwendong/videogen/2264_with_audio/metadata_audio_npy.jsonl"), allowed_tasks=("audio_only",), ), "psi0_dance_audio": SourcePreset( name="psi0_dance_audio", modality="audio", dataset_root=Path("/cpfs01/thscc/sharestorage/AIGC-06-01/Hithink_VideoGen_Group/user_workspace/buwendong/user/code/dance_1723_video_psi0/dance_1723_video_10s"), manifest_path=Path( "/cpfs01/thscc/sharestorage/AIGC-06-01/Hithink_VideoGen_Group/user_workspace/buwendong/user/code/dance_1723_video_psi0/dance_1723_video_10s/metadata_audio_npy.jsonl" ), allowed_tasks=("audio_only",), ), "qwen3_tts_seed_audio_command": SourcePreset( name="qwen3_tts_seed_audio_command", modality="audio", dataset_root=Path("/cpfs01/thscc/sharestorage/AIGC-06-01/Hithink_VideoGen_Group/user_workspace/buwendong/user/code/qwen3-tts"), manifest_path=Path("/cpfs01/thscc/sharestorage/AIGC-06-01/Hithink_VideoGen_Group/user_workspace/buwendong/user/code/qwen3-tts/metadata_audio_npy.jsonl"), allowed_tasks=("audio_command_text", "audio_command_only"), instruction_key="content_short_description", is_audio_dir_manifest=True, ), "dance_1723_video_10s_clip50": SourcePreset( name="dance_1723_video_10s_clip50", modality="video_clip", dataset_root=Path("/cpfs01/thscc/sharestorage/AIGC-06-01/Hithink_VideoGen_Group/user_workspace/yetinghong/videogen/psi0_video_clip_50f_dense_stride1_direct_full/dance_1723_video_10s"), manifest_path=Path( "/cpfs01/thscc/sharestorage/AIGC-06-01/Hithink_VideoGen_Group/user_workspace/yetinghong/videogen/psi0_video_clip_50f_dense_stride1_direct_full/dance_1723_video_10s/metadata.jsonl" ), allowed_tasks=("video_clip_text", "video_clip_only"), instruction_key="video_caption", video_embed_dir=Path( "/cpfs01/thscc/sharestorage/AIGC-06-01/Hithink_VideoGen_Group/user_workspace/yetinghong/videogen/psi0_video_clip_50f_dense_stride1_direct_full/dance_1723_video_10s/embeds" ), ), "motion_example_0506_demo_clip50": SourcePreset( name="motion_example_0506_demo_clip50", modality="video_clip", dataset_root=Path( "/cpfs01/thscc/sharestorage/AIGC-06-01/Hithink_VideoGen_Group/user_workspace/yetinghong/videogen/psi0_video_clip_50f_dense_stride1_direct_full/motion_example_0506_demo" ), manifest_path=Path( "/cpfs01/thscc/sharestorage/AIGC-06-01/Hithink_VideoGen_Group/user_workspace/yetinghong/videogen/psi0_video_clip_50f_dense_stride1_direct_full/motion_example_0506_demo/metadata.jsonl" ), allowed_tasks=("video_clip_text", "video_clip_only"), instruction_key="video_caption", video_embed_dir=Path( "/cpfs01/thscc/sharestorage/AIGC-06-01/Hithink_VideoGen_Group/user_workspace/yetinghong/videogen/psi0_video_clip_50f_dense_stride1_direct_full/motion_example_0506_demo/embeds" ), ), "2264_with_audio_clip50": SourcePreset( name="2264_with_audio_clip50", modality="video_clip", dataset_root=Path("/cpfs01/thscc/sharestorage/AIGC-06-01/Hithink_VideoGen_Group/user_workspace/yetinghong/videogen/psi0_video_clip_50f_dense_stride1_direct_full/2264_with_audio"), manifest_path=Path( "/cpfs01/thscc/sharestorage/AIGC-06-01/Hithink_VideoGen_Group/user_workspace/yetinghong/videogen/psi0_video_clip_50f_dense_stride1_direct_full/2264_with_audio/metadata.jsonl" ), allowed_tasks=("video_clip_text", "video_clip_only"), instruction_key="video_caption", video_embed_dir=Path( "/cpfs01/thscc/sharestorage/AIGC-06-01/Hithink_VideoGen_Group/user_workspace/yetinghong/videogen/psi0_video_clip_50f_dense_stride1_direct_full/2264_with_audio/embeds" ), ), } _VIDEO_EMBED_INFO_CACHE: dict[str, dict[str, Any]] = {} @dataclass class ExportItem: source_name: str task_name: str modality: str input_path: Path output_path: Path instruction: str manifest_id: str rel_source_path: str def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description="Cache Qwen2.5-Omni thinker hidden states for stable multimodal tasks.") parser.add_argument("--mode", choices=("estimate", "benchmark", "export"), default="estimate") parser.add_argument("--model-path", default="/cpfs01/VideoGen/public_ckpt/Qwen/Qwen2.5-Omni-3B") parser.add_argument( "--output-root", default="/cpfs01/thscc/sharestorage/AIGC-06-01/Hithink_VideoGen_Group/user_workspace/yetinghong/videogen/psi0_omni_hidden_states_v20", ) parser.add_argument("--tasks", default="audio_only,audio_command_text,audio_command_only,video_clip_text,video_clip_only") parser.add_argument( "--sources", default="2264_with_audio,psi0_dance_audio,qwen3_tts_seed_audio_command,dance_1723_video_10s_clip50,motion_example_0506_demo_clip50,2264_with_audio_clip50", ) parser.add_argument("--estimate-samples-per-group", type=int, default=32) parser.add_argument("--benchmark-samples", type=int, default=256) parser.add_argument("--limit", type=int, default=0) parser.add_argument("--audio-batch-size", type=int, default=16) parser.add_argument("--video-batch-size", type=int, default=8) parser.add_argument("--num-io-workers", type=int, default=8) parser.add_argument("--num-save-workers", type=int, default=2) parser.add_argument("--max-pending-save-batches", type=int, default=2) parser.add_argument("--save-dtype", choices=("bf16", "fp16", "fp32"), default="bf16") parser.add_argument("--overwrite", action="store_true") parser.add_argument("--confirm-full-video", action="store_true") return parser.parse_args() def parse_csv_list(raw: str) -> list[str]: return [part.strip() for part in str(raw).split(",") if part.strip()] def rank() -> int: return int(os.environ.get("RANK", "0")) def world_size() -> int: return int(os.environ.get("WORLD_SIZE", "1")) def is_rank0() -> bool: return rank() == 0 def log(msg: str) -> None: if is_rank0(): print(msg, flush=True) def sanitize_rel_path(path: Path) -> str: return str(path).replace("\\", "/") def count_jsonl_rows(path: Path) -> int: count = 0 with path.open("rb") as f: for chunk in iter(lambda: f.read(1024 * 1024 * 16), b""): count += chunk.count(b"\n") return count def maybe_init_distributed() -> None: if world_size() <= 1 or dist.is_initialized(): return backend = "nccl" if torch.cuda.is_available() else "gloo" dist.init_process_group(backend=backend) def cleanup_distributed() -> None: if dist.is_initialized(): dist.destroy_process_group() def current_device() -> torch.device: if torch.cuda.is_available(): local_rank = int(os.environ.get("LOCAL_RANK", "0")) torch.cuda.set_device(local_rank) return torch.device(f"cuda:{local_rank}") return torch.device("cpu") def save_dtype_from_arg(arg: str) -> torch.dtype: if arg == "bf16": return torch.bfloat16 if arg == "fp16": return torch.float16 return torch.float32 def model_dtype_for_device(device: torch.device, arg: str) -> torch.dtype: if device.type == "cuda": return save_dtype_from_arg(arg) return torch.float32 def load_hidden_size(model_path: str) -> int: cfg = AutoConfig.from_pretrained(model_path, trust_remote_code=True) thinker_cfg = getattr(cfg, "thinker_config", None) if thinker_cfg is None: raise ValueError(f"Model config at {model_path} has no thinker_config") text_cfg = thinker_cfg.get("text_config", thinker_cfg) if isinstance(thinker_cfg, dict) else thinker_cfg.text_config hidden_size = text_cfg.get("hidden_size") if isinstance(text_cfg, dict) else getattr(text_cfg, "hidden_size", None) if hidden_size is None: raise ValueError(f"Cannot find hidden_size in thinker_config.text_config for {model_path}") return int(hidden_size) def load_processor(model_path: str) -> Qwen2_5OmniProcessor: return Qwen2_5OmniProcessor.from_pretrained(model_path, use_fast=False) def load_model(model_path: str, device: torch.device, save_dtype: torch.dtype) -> Qwen2_5OmniThinkerForConditionalGeneration: model = Qwen2_5OmniThinkerForConditionalGeneration.from_pretrained( model_path, dtype=model_dtype_for_device( device, "bf16" if save_dtype == torch.bfloat16 else "fp16" if save_dtype == torch.float16 else "fp32", ), device_map=None, ) model.eval().to(device) return model def stable_pool_prompt(prompt_pools: dict[str, list[str]], key: str) -> str: layouts = list(prompt_pools.keys()) layout_digest = hashlib.sha1(f"{key}::layout".encode("utf-8")).digest() layout = layouts[int.from_bytes(layout_digest[:8], "big") % len(layouts)] prompts = prompt_pools[layout] prompt_digest = hashlib.sha1(f"{key}::prompt".encode("utf-8")).digest() return str(prompts[int.from_bytes(prompt_digest[:8], "big") % len(prompts)]).strip() def instruction_identity(row: dict[str, Any]) -> str: for key in ("id", "filename", "name", "audio_path", "video_path"): value = row.get(key) if value not in (None, ""): return str(value) return json.dumps(row, sort_keys=True, ensure_ascii=False) def instruction_for_item(source_name: str, task_name: str, row: dict[str, Any]) -> str: if task_name in ("audio_only", "audio_command_only", "video_clip_only"): return "" key = f"{source_name}::{task_name}::{instruction_identity(row)}" if task_name == "audio_command_text": return stable_pool_prompt(_AUDIO_COMMAND_PROMPT_POOLS, key) if task_name == "video_clip_text": return stable_pool_prompt(_VIDEO_MOTION_PROMPT_POOLS, key) return "" def rel_to_root(path: Path, root: Path) -> Path: try: return path.relative_to(root) except ValueError: return Path(path.name) def resolve_audio_output_path(output_root: Path, source_name: str, task_name: str, input_path: Path, dataset_root: Path) -> Path: rel = rel_to_root(input_path, dataset_root).with_suffix(".safetensors") return output_root / "audio" / source_name / task_name / rel def resolve_video_output_path(output_root: Path, source_name: str, task_name: str, embed_path: Path) -> Path: return output_root / "video_clip" / source_name / task_name / f"{embed_path.stem}.safetensors" def iter_jsonl_rows(path: Path) -> Iterator[tuple[int, dict[str, Any]]]: with path.open("r", encoding="utf-8") as f: for idx, line in enumerate(f): line = line.strip() if not line: continue yield idx, json.loads(line) def iter_audio_items(preset: SourcePreset, task_name: str, output_root: Path) -> Iterator[ExportItem]: seen: set[str] = set() seen_audio_dirs: set[str] = set() for row_idx, row in iter_jsonl_rows(preset.manifest_path): instruction = instruction_for_item(preset.name, task_name, row) raw_path = row.get(preset.audio_path_key) if not raw_path: continue audio_path = preset.dataset_root / str(raw_path) if preset.is_audio_dir_manifest: dir_key = str(audio_path) if dir_key in seen_audio_dirs: continue seen_audio_dirs.add(dir_key) if not audio_path.is_dir(): continue for npy_path in sorted(audio_path.glob("*.npy")): key = str(npy_path) if key in seen: continue seen.add(key) yield ExportItem( source_name=preset.name, task_name=task_name, modality="audio", input_path=npy_path, output_path=resolve_audio_output_path(output_root, preset.name, task_name, npy_path, preset.dataset_root), instruction=instruction, manifest_id=str(row.get("filename", row.get("id", row_idx))), rel_source_path=sanitize_rel_path(rel_to_root(npy_path, preset.dataset_root)), ) else: if not audio_path.exists(): continue key = str(audio_path) if key in seen: continue seen.add(key) yield ExportItem( source_name=preset.name, task_name=task_name, modality="audio", input_path=audio_path, output_path=resolve_audio_output_path(output_root, preset.name, task_name, audio_path, preset.dataset_root), instruction=instruction, manifest_id=str(row.get("id", row.get("name", row_idx))), rel_source_path=sanitize_rel_path(rel_to_root(audio_path, preset.dataset_root)), ) def find_video_embed_path(preset: SourcePreset, row: dict[str, Any]) -> Path | None: assert preset.video_embed_dir is not None video_value = row.get(preset.video_path_key) or row.get("video_path") if not video_value: return None stem = Path(str(video_value)).stem manifest_info = _VIDEO_EMBED_INFO_CACHE.get(preset.name) if manifest_info is None: manifest_path = preset.video_embed_dir / "manifest.json" if manifest_path.exists(): manifest_info = json.loads(manifest_path.read_text(encoding="utf-8")) else: manifest_info = {} _VIDEO_EMBED_INFO_CACHE[preset.name] = manifest_info fps_value = manifest_info.get("video_sample_fps") size_value = manifest_info.get("video_size_pixels") if fps_value is not None and size_value is not None: fps_token = str(fps_value).replace(".", "p") direct_path = preset.video_embed_dir / f"{stem}.fps{fps_token}.size{size_value}.npz" if direct_path.exists(): return direct_path matches = sorted(preset.video_embed_dir.glob(f"{stem}.fps*.size*.npz")) if not matches: return None return matches[0] def iter_video_items(preset: SourcePreset, task_name: str, output_root: Path) -> Iterator[ExportItem]: for row_idx, row in iter_jsonl_rows(preset.manifest_path): instruction = instruction_for_item(preset.name, task_name, row) embed_path = find_video_embed_path(preset, row) if embed_path is None or not embed_path.exists(): continue yield ExportItem( source_name=preset.name, task_name=task_name, modality="video_clip", input_path=embed_path, output_path=resolve_video_output_path(output_root, preset.name, task_name, embed_path), instruction=instruction, manifest_id=str(row.get("id", row.get("name", row_idx))), rel_source_path=sanitize_rel_path(embed_path.name), ) def iter_group_items(preset: SourcePreset, task_name: str, output_root: Path) -> Iterator[ExportItem]: if preset.modality == "audio": yield from iter_audio_items(preset, task_name, output_root) return yield from iter_video_items(preset, task_name, output_root) def count_group_items(preset: SourcePreset, task_name: str, output_root: Path) -> int: if preset.modality == "video_clip": assert preset.video_embed_dir is not None manifest_path = preset.video_embed_dir / "manifest.json" if manifest_path.exists(): manifest = json.loads(manifest_path.read_text(encoding="utf-8")) total = manifest.get("total_count", manifest.get("count")) if total is not None: return int(total) return count_jsonl_rows(preset.manifest_path) return sum(1 for _ in iter_group_items(preset, task_name, output_root)) def should_keep_item(global_index: int, total: int, sample_count: int) -> bool: if sample_count <= 0: return False if total <= sample_count: return True step = max(1, total // sample_count) return global_index % step == 0 def sampled_group_items( preset: SourcePreset, task_name: str, output_root: Path, sample_count: int, ) -> list[ExportItem]: if preset.modality == "video_clip": sampled: list[ExportItem] = [] for item in iter_group_items(preset, task_name, output_root): sampled.append(item) if len(sampled) >= sample_count: break return sampled total = count_group_items(preset, task_name, output_root) sampled: list[ExportItem] = [] for idx, item in enumerate(iter_group_items(preset, task_name, output_root)): if should_keep_item(idx, total, sample_count): sampled.append(item) if len(sampled) >= sample_count: break return sampled def source_task_pairs(tasks: list[str], sources: list[str]) -> list[tuple[SourcePreset, str]]: pairs: list[tuple[SourcePreset, str]] = [] for source_name in sources: preset = SOURCE_PRESETS[source_name] for task_name in tasks: if task_name in preset.allowed_tasks: pairs.append((preset, task_name)) return pairs def load_audio_payload(item: ExportItem) -> dict[str, Any]: audio = np.load(item.input_path, allow_pickle=False).astype(np.float32, copy=False).reshape(-1) return { "audio": audio, "instruction": item.instruction, } def load_video_payload(item: ExportItem) -> dict[str, Any]: with np.load(item.input_path, allow_pickle=False) as cache: return { "pixel_values_videos": cache["pixel_values_videos"], "video_grid_thw": cache["video_grid_thw"], "video_second_per_grid": cache["video_second_per_grid"], "instruction": item.instruction, } def build_audio_text(processor: Qwen2_5OmniProcessor, instructions: list[str]) -> list[str]: texts: list[str] = [] for instruction in instructions: content = [{"type": "audio", "audio": "audio.wav"}] if instruction: content.append({"type": "text", "text": instruction}) messages = [[ {"role": "system", "content": [{"type": "text", "text": OMNI_DEFAULT_SYSTEM_PROMPT}]}, {"role": "user", "content": content}, ]] texts.append(processor.apply_chat_template(messages[0], tokenize=False, add_generation_prompt=True)) return texts def build_video_text(processor: Qwen2_5OmniProcessor, instructions: list[str]) -> list[str]: texts: list[str] = [] for instruction in instructions: content = [{"type": "video", "video": "video.mp4"}] if instruction: content.append({"type": "text", "text": instruction}) messages = [[ {"role": "system", "content": [{"type": "text", "text": OMNI_DEFAULT_SYSTEM_PROMPT}]}, {"role": "user", "content": content}, ]] texts.append(processor.apply_chat_template(messages[0], tokenize=False, add_generation_prompt=True)) return texts def collate_audio_batch( processor: Qwen2_5OmniProcessor, payloads: list[dict[str, Any]], device: torch.device, ) -> dict[str, torch.Tensor]: texts = build_audio_text(processor, [payload["instruction"] for payload in payloads]) audios = [np.asarray(payload["audio"], dtype=np.float32) for payload in payloads] inputs = processor(text=texts, audio=audios, padding=True, return_tensors="pt") return {key: value.to(device) if hasattr(value, "to") else value for key, value in inputs.items()} def collate_video_batch( processor: Qwen2_5OmniProcessor, payloads: list[dict[str, Any]], device: torch.device, ) -> dict[str, torch.Tensor]: texts = build_video_text(processor, [payload["instruction"] for payload in payloads]) grids_for_replace = [payload["video_grid_thw"][0] for payload in payloads] seconds_for_replace = [float(np.asarray(payload["video_second_per_grid"]).reshape(-1)[0]) for payload in payloads] texts = processor.replace_multimodal_special_tokens( texts, iter([]), iter([]), iter(grids_for_replace), iter(seconds_for_replace), False, 25, 2.0, ) text_inputs = processor.tokenizer(texts, padding=True, return_tensors="pt") inputs = {key: value.to(device) for key, value in text_inputs.items()} inputs["pixel_values_videos"] = torch.cat( [torch.as_tensor(payload["pixel_values_videos"], dtype=torch.float32, device=device) for payload in payloads], dim=0, ) inputs["video_grid_thw"] = torch.cat( [torch.as_tensor(payload["video_grid_thw"], dtype=torch.long, device=device) for payload in payloads], dim=0, ) inputs["video_second_per_grid"] = torch.cat( [ torch.as_tensor(payload["video_second_per_grid"], dtype=torch.float32, device=device).reshape(-1) for payload in payloads ], dim=0, ) return inputs def omni_hidden_states_without_lm_head( model: Qwen2_5OmniThinkerForConditionalGeneration, vlm_kwargs: dict[str, torch.Tensor], ) -> torch.Tensor: input_ids = vlm_kwargs.get("input_ids") attention_mask = vlm_kwargs.get("attention_mask") input_features = vlm_kwargs.get("input_features") pixel_values = vlm_kwargs.get("pixel_values") pixel_values_videos = vlm_kwargs.get("pixel_values_videos") image_grid_thw = vlm_kwargs.get("image_grid_thw") video_grid_thw = vlm_kwargs.get("video_grid_thw") feature_attention_mask = vlm_kwargs.get("feature_attention_mask") audio_feature_lengths = vlm_kwargs.get("audio_feature_lengths") video_second_per_grid = vlm_kwargs.get("video_second_per_grid") inputs_embeds = vlm_kwargs.get("inputs_embeds") position_ids = vlm_kwargs.get("position_ids") cache_position = vlm_kwargs.get("cache_position") use_audio_in_video = vlm_kwargs.get("use_audio_in_video") if inputs_embeds is None: inputs_embeds = model.get_input_embeddings()(input_ids) if input_features is not None: audio_features = model.get_audio_features( input_features, feature_attention_mask=feature_attention_mask, audio_feature_lengths=audio_feature_lengths, ) audio_features = audio_features.to(inputs_embeds.device, inputs_embeds.dtype) _, _, audio_mask = model.get_placeholder_mask(input_ids, inputs_embeds=inputs_embeds) inputs_embeds = inputs_embeds.masked_scatter(audio_mask, audio_features) if pixel_values is not None: image_embeds = model.get_image_features(pixel_values, image_grid_thw) image_embeds = image_embeds.to(inputs_embeds.device, inputs_embeds.dtype) image_mask, _, _ = model.get_placeholder_mask( input_ids, inputs_embeds=inputs_embeds, image_features=image_embeds, ) inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds) if pixel_values_videos is not None: video_embeds = model.get_video_features(pixel_values_videos, video_grid_thw) video_embeds = video_embeds.to(inputs_embeds.device, inputs_embeds.dtype) _, video_mask, _ = model.get_placeholder_mask( input_ids, inputs_embeds=inputs_embeds, video_features=video_embeds, ) inputs_embeds = inputs_embeds.masked_scatter(video_mask, video_embeds) if feature_attention_mask is not None: audio_feature_lengths = torch.sum(feature_attention_mask, dim=1) else: audio_feature_lengths = None if attention_mask is not None and position_ids is None: if cache_position is None or (cache_position is not None and cache_position[0] == 0) or model.rope_deltas is None: delta0 = (1 - attention_mask).sum(dim=-1).unsqueeze(1) position_ids, rope_deltas = model.get_rope_index( input_ids, image_grid_thw, video_grid_thw, attention_mask, use_audio_in_video, audio_feature_lengths, video_second_per_grid, ) model.rope_deltas = rope_deltas - delta0 else: batch_size, seq_length = input_ids.shape delta = cache_position[0] + model.rope_deltas if cache_position is not None else 0 position_ids = torch.arange(seq_length, device=input_ids.device) position_ids = position_ids.view(1, -1).expand(batch_size, -1) position_ids = position_ids.add(delta) position_ids = position_ids.unsqueeze(0).expand(3, -1, -1) outputs = model.model( attention_mask=attention_mask, position_ids=position_ids, past_key_values=vlm_kwargs.get("past_key_values"), inputs_embeds=inputs_embeds, use_cache=False, output_attentions=vlm_kwargs.get("output_attentions"), output_hidden_states=True, return_dict=True, cache_position=cache_position, ) return outputs.hidden_states[-1] def save_hidden_state( item: ExportItem, hidden_states: torch.Tensor, save_dtype: torch.dtype, overwrite: bool, ) -> tuple[bool, int]: if item.output_path.exists() and not overwrite: return False, 0 item.output_path.parent.mkdir(parents=True, exist_ok=True) payload = {"hidden_states": hidden_states.to(dtype=save_dtype).cpu().contiguous()} metadata = { "source_name": item.source_name, "task_name": item.task_name, "modality": item.modality, "manifest_id": item.manifest_id, "source_path": item.rel_source_path, "instruction_sha1": hashlib.sha1(item.instruction.encode("utf-8")).hexdigest(), } tmp_path = item.output_path.with_name(f".{item.output_path.name}.{os.getpid()}.tmp") save_file(payload, str(tmp_path), metadata=metadata) os.replace(tmp_path, item.output_path) return True, item.output_path.stat().st_size def save_hidden_state_cpu( item: ExportItem, hidden_states: torch.Tensor, overwrite: bool, ) -> tuple[bool, int]: if item.output_path.exists() and not overwrite: return False, 0 item.output_path.parent.mkdir(parents=True, exist_ok=True) payload = {"hidden_states": hidden_states.contiguous()} metadata = { "source_name": item.source_name, "task_name": item.task_name, "modality": item.modality, "manifest_id": item.manifest_id, "source_path": item.rel_source_path, "instruction_sha1": hashlib.sha1(item.instruction.encode("utf-8")).hexdigest(), } tmp_path = item.output_path.with_name(f".{item.output_path.name}.{os.getpid()}.tmp") save_file(payload, str(tmp_path), metadata=metadata) os.replace(tmp_path, item.output_path) return True, item.output_path.stat().st_size def load_payloads( items: list[ExportItem], num_io_workers: int, io_executor: ThreadPoolExecutor | None = None, ) -> list[dict[str, Any]]: loader = load_audio_payload if items[0].modality == "audio" else load_video_payload if num_io_workers <= 1 or len(items) == 1: return [loader(item) for item in items] if io_executor is not None: return list(io_executor.map(loader, items)) with ThreadPoolExecutor(max_workers=num_io_workers) as executor: return list(executor.map(loader, items)) def is_cuda_oom(exc: Exception) -> bool: if isinstance(exc, torch.OutOfMemoryError): return True message = str(exc).lower() return "out of memory" in message and "cuda" in message def save_hidden_state_batch_cpu( items: list[ExportItem], hidden_cpu: torch.Tensor, seq_lens: list[int], overwrite: bool, ) -> dict[str, Any]: stats = { "written": 0, "skipped": 0, "failed": 0, "hidden_bytes": 0, "error": None, } for batch_idx, batch_item in enumerate(items): seq_len = int(seq_lens[batch_idx]) sample_hidden = hidden_cpu[batch_idx, :seq_len, :] try: did_write, file_bytes = save_hidden_state_cpu(batch_item, sample_hidden, overwrite) if did_write: stats["written"] += 1 stats["hidden_bytes"] += int(file_bytes) else: stats["skipped"] += 1 except Exception as exc: # noqa: BLE001 error = f"{batch_item.source_name}/{batch_item.task_name}: {type(exc).__name__}: {exc}" stats["failed"] += 1 if stats["error"] is None: stats["error"] = error if is_rank0(): print(f"[ERROR] {error}", flush=True) traceback.print_exc() return stats def process_export_batch( preset: SourcePreset, task_name: str, items: list[ExportItem], args: argparse.Namespace, processor: Qwen2_5OmniProcessor, model: Qwen2_5OmniThinkerForConditionalGeneration, device: torch.device, save_dtype: torch.dtype, io_executor: ThreadPoolExecutor | None = None, save_executor: ThreadPoolExecutor | None = None, preloaded_payloads: list[dict[str, Any]] | None = None, ) -> dict[str, Any]: payloads: list[dict[str, Any]] | None = None inputs: dict[str, torch.Tensor] | None = None hidden: torch.Tensor | None = None hidden_cpu: torch.Tensor | None = None try: payloads = preloaded_payloads if preloaded_payloads is not None else load_payloads( items, int(args.num_io_workers), io_executor=io_executor, ) if preset.modality == "audio": inputs = collate_audio_batch(processor, payloads, device) else: inputs = collate_video_batch(processor, payloads, device) with torch.inference_mode(): hidden = omni_hidden_states_without_lm_head(model, inputs) attention_mask = inputs["attention_mask"] seq_lens = [int(v) for v in attention_mask.sum(dim=1).tolist()] hidden_cpu = hidden.to(dtype=save_dtype).cpu().contiguous() stats = { "processed": len(items), "written": 0, "skipped": 0, "failed": 0, "hidden_tokens": int(sum(seq_lens)), "hidden_bytes": 0, "seq_sum": int(sum(seq_lens)), "error": None, "pending_saves": [], } overwrite = args.overwrite if args.mode == "export" else True if save_executor is None: save_stats = save_hidden_state_batch_cpu(items, hidden_cpu, seq_lens, overwrite) stats["written"] += int(save_stats["written"]) stats["skipped"] += int(save_stats["skipped"]) stats["failed"] += int(save_stats["failed"]) stats["hidden_bytes"] += int(save_stats["hidden_bytes"]) stats["error"] = save_stats["error"] else: stats["pending_saves"].append( save_executor.submit(save_hidden_state_batch_cpu, items, hidden_cpu, seq_lens, overwrite) ) del hidden del hidden_cpu del inputs del payloads return stats except Exception as exc: # noqa: BLE001 error = f"{preset.name}/{task_name}: {type(exc).__name__}: {exc}" if hidden is not None: del hidden hidden = None if hidden_cpu is not None: del hidden_cpu hidden_cpu = None if inputs is not None: del inputs inputs = None if payloads is not None: del payloads payloads = None gc.collect() if device.type == "cuda": torch.cuda.empty_cache() if is_cuda_oom(exc) and len(items) > 1: left_size = len(items) // 2 right_size = len(items) - left_size if is_rank0(): print( f"[WARN] {error} | retry split batch {len(items)} -> {left_size} + {right_size}", flush=True, ) left_stats = process_export_batch( preset, task_name, items[:left_size], args, processor, model, device, save_dtype, io_executor=io_executor, save_executor=save_executor, preloaded_payloads=payloads[:left_size] if payloads is not None else None, ) right_stats = process_export_batch( preset, task_name, items[left_size:], args, processor, model, device, save_dtype, io_executor=io_executor, save_executor=save_executor, preloaded_payloads=payloads[left_size:] if payloads is not None else None, ) merged = { "processed": left_stats["processed"] + right_stats["processed"], "written": left_stats["written"] + right_stats["written"], "skipped": left_stats["skipped"] + right_stats["skipped"], "failed": left_stats["failed"] + right_stats["failed"], "hidden_tokens": left_stats["hidden_tokens"] + right_stats["hidden_tokens"], "hidden_bytes": left_stats["hidden_bytes"] + right_stats["hidden_bytes"], "seq_sum": left_stats["seq_sum"] + right_stats["seq_sum"], "error": left_stats["error"] or right_stats["error"] or error, "pending_saves": [*left_stats.get("pending_saves", []), *right_stats.get("pending_saves", [])], } return merged if is_rank0(): print(f"[ERROR] {error}", flush=True) traceback.print_exc() return { "processed": 0, "written": 0, "skipped": 0, "failed": len(items), "hidden_tokens": 0, "hidden_bytes": 0, "seq_sum": 0, "error": error, "pending_saves": [], } def collect_completed_save_futures( pending_saves: deque[Future[dict[str, Any]]], *, wait_for_one: bool, ) -> list[dict[str, Any]]: if not pending_saves: return [] future_list = list(pending_saves) if wait_for_one: done, _ = wait(future_list, return_when=FIRST_COMPLETED) else: done, _ = wait(future_list, timeout=0, return_when=FIRST_COMPLETED) if not done: return [] done_ids = {id(fut) for fut in done} results: list[dict[str, Any]] = [] remaining: deque[Future[dict[str, Any]]] = deque() for fut in pending_saves: if id(fut) in done_ids: results.append(fut.result()) else: remaining.append(fut) pending_saves.clear() pending_saves.extend(remaining) return results def bench_or_export_group( preset: SourcePreset, task_name: str, args: argparse.Namespace, processor: Qwen2_5OmniProcessor, model: Qwen2_5OmniThinkerForConditionalGeneration, device: torch.device, save_dtype: torch.dtype, group_output_root: Path, ) -> dict[str, Any]: if args.mode == "benchmark": global_total = int(args.benchmark_samples) elif args.limit > 0: global_total = int(args.limit) else: global_total = count_group_items(preset, task_name, group_output_root) local_total = global_total // world_size() + (1 if rank() < (global_total % world_size()) else 0) progress = tqdm( total=local_total, desc=f"{preset.name}/{task_name} rank{rank()}", disable=not is_rank0(), unit="item", ) batch_size = int(args.audio_batch_size if preset.modality == "audio" else args.video_batch_size) group_items: list[ExportItem] = [] processed = 0 written = 0 skipped = 0 failed = 0 hidden_tokens = 0 hidden_bytes = 0 seq_sum = 0 first_error: str | None = None started = time.time() max_pending_save_batches = max(1, int(args.max_pending_save_batches)) pending_saves: deque[Future[dict[str, Any]]] = deque() def merge_save_stats(save_stats: dict[str, Any]) -> None: nonlocal written, skipped, failed, hidden_bytes, first_error written += int(save_stats["written"]) skipped += int(save_stats["skipped"]) failed += int(save_stats["failed"]) hidden_bytes += int(save_stats["hidden_bytes"]) if first_error is None and save_stats.get("error"): first_error = str(save_stats["error"]) def iter_local_batches() -> Iterator[list[ExportItem]]: batch: list[ExportItem] = [] for global_index, item in enumerate(iter_group_items(preset, task_name, group_output_root)): if global_index >= global_total: break if global_index % world_size() != rank(): continue if args.mode == "export" and item.output_path.exists() and not args.overwrite: nonlocal skipped skipped += 1 progress.update(1) progress.set_postfix(processed=processed, written=written, skipped=skipped, failed=failed) continue batch.append(item) if len(batch) >= batch_size: yield batch batch = [] if batch: yield batch with ThreadPoolExecutor(max_workers=max(1, int(args.num_io_workers))) as io_executor, \ ThreadPoolExecutor(max_workers=max(1, int(args.num_save_workers))) as save_executor, \ ThreadPoolExecutor(max_workers=2) as prefetch_executor: batch_iter = iter_local_batches() current_items = next(batch_iter, None) current_payload_future: Future[list[dict[str, Any]]] | None = None next_items: list[ExportItem] | None = None next_payload_future: Future[list[dict[str, Any]]] | None = None if current_items is not None: current_payload_future = prefetch_executor.submit( load_payloads, current_items, int(args.num_io_workers), io_executor, ) while current_items is not None and current_payload_future is not None: next_items = next(batch_iter, None) if next_items is not None: next_payload_future = prefetch_executor.submit( load_payloads, next_items, int(args.num_io_workers), io_executor, ) else: next_payload_future = None batch_stats = process_export_batch( preset, task_name, current_items, args, processor, model, device, save_dtype, io_executor=io_executor, save_executor=save_executor, preloaded_payloads=current_payload_future.result(), ) processed += int(batch_stats["processed"]) failed += int(batch_stats["failed"]) hidden_tokens += int(batch_stats["hidden_tokens"]) seq_sum += int(batch_stats["seq_sum"]) if first_error is None and batch_stats["error"]: first_error = str(batch_stats["error"]) for fut in batch_stats.get("pending_saves", []): pending_saves.append(fut) while len(pending_saves) >= max_pending_save_batches: completed = collect_completed_save_futures(pending_saves, wait_for_one=True) for save_stats in completed: merge_save_stats(save_stats) for save_stats in collect_completed_save_futures(pending_saves, wait_for_one=False): merge_save_stats(save_stats) progress.update(len(current_items)) progress.set_postfix(processed=processed, written=written, skipped=skipped, failed=failed) current_items = next_items current_payload_future = next_payload_future while pending_saves: for save_stats in collect_completed_save_futures(pending_saves, wait_for_one=True): merge_save_stats(save_stats) progress.close() elapsed = time.time() - started metrics = torch.tensor( [processed, written, skipped, failed, hidden_tokens, hidden_bytes, seq_sum], dtype=torch.float64, device=device, ) wall = torch.tensor([elapsed], dtype=torch.float64, device=device) if dist.is_initialized(): dist.all_reduce(metrics, op=dist.ReduceOp.SUM) dist.all_reduce(wall, op=dist.ReduceOp.MAX) total_processed, total_written, total_skipped, total_failed, total_tokens, total_bytes, total_seq_sum = metrics.tolist() wall_sec = float(wall.item()) avg_seq_len = (total_seq_sum / total_processed) if total_processed > 0 else 0.0 samples_per_sec = (total_processed / wall_sec) if wall_sec > 0 else 0.0 tokens_per_sec = (total_tokens / wall_sec) if wall_sec > 0 else 0.0 avg_file_mb = (total_bytes / max(total_written, 1)) / (1024 ** 2) group_stats = { "source_name": preset.name, "task_name": task_name, "global_total": int(global_total), "processed": int(total_processed), "written": int(total_written), "skipped": int(total_skipped), "failed": int(total_failed), "elapsed_sec": wall_sec, "samples_per_sec": samples_per_sec, "tokens_per_sec": tokens_per_sec, "avg_seq_len": avg_seq_len, "avg_output_mb": avg_file_mb, "first_error": first_error or "", } return group_stats def estimate_group( preset: SourcePreset, task_name: str, args: argparse.Namespace, processor: Qwen2_5OmniProcessor, hidden_size: int, ) -> dict[str, Any]: sample_items = sampled_group_items( preset, task_name, Path(args.output_root), int(args.estimate_samples_per_group), ) if not sample_items: return { "source_name": preset.name, "task_name": task_name, "total_items": 0, "sample_count": 0, } seq_lens: list[int] = [] output_bytes: list[int] = [] payloads = load_payloads(sample_items, int(args.num_io_workers)) sample_progress = tqdm( payloads, total=len(payloads), desc=f"Estimate {preset.name}/{task_name}", disable=not is_rank0(), leave=False, unit="sample", ) if preset.modality == "audio": for payload in sample_progress: texts = build_audio_text(processor, [payload["instruction"]]) inputs = processor( text=texts, audio=[np.asarray(payload["audio"], dtype=np.float32)], padding=True, return_tensors="pt", ) seq_len = int(inputs["input_ids"].shape[1]) seq_lens.append(seq_len) output_bytes.append(seq_len * hidden_size * torch.tensor([], dtype=save_dtype_from_arg(args.save_dtype)).element_size()) else: for payload in sample_progress: texts = build_video_text(processor, [payload["instruction"]]) texts = processor.replace_multimodal_special_tokens( texts, iter([]), iter([]), iter([payload["video_grid_thw"][0]]), iter([float(np.asarray(payload["video_second_per_grid"]).reshape(-1)[0])]), False, 25, 2.0, ) tokenized = processor.tokenizer(texts, padding=True, return_tensors="pt") seq_len = int(tokenized["input_ids"].shape[1]) seq_lens.append(seq_len) output_bytes.append(seq_len * hidden_size * torch.tensor([], dtype=save_dtype_from_arg(args.save_dtype)).element_size()) sample_progress.close() total_items = count_group_items(preset, task_name, Path(args.output_root)) avg_seq_len = float(sum(seq_lens) / len(seq_lens)) avg_output_bytes = float(sum(output_bytes) / len(output_bytes)) return { "source_name": preset.name, "task_name": task_name, "total_items": int(total_items), "sample_count": len(seq_lens), "avg_seq_len": avg_seq_len, "min_seq_len": int(min(seq_lens)), "max_seq_len": int(max(seq_lens)), "avg_output_mb": avg_output_bytes / (1024 ** 2), "estimated_total_gib": total_items * avg_output_bytes / (1024 ** 3), "estimated_total_tib": total_items * avg_output_bytes / (1024 ** 4), } def ensure_video_export_is_confirmed(args: argparse.Namespace, pairs: list[tuple[SourcePreset, str]]) -> None: if args.mode != "export": return has_video = any(preset.modality == "video_clip" for preset, _ in pairs) if has_video and not args.confirm_full_video: raise ValueError("video_clip export is disabled by default; re-run with --confirm-full-video") def write_report(output_root: Path, mode: str, report: dict[str, Any]) -> Path: report_dir = output_root / "_reports" report_dir.mkdir(parents=True, exist_ok=True) timestamp = time.strftime("%Y%m%d_%H%M%S") path = report_dir / f"{mode}.{timestamp}.json" path.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8") return path def run_estimate(args: argparse.Namespace, pairs: list[tuple[SourcePreset, str]]) -> None: hidden_size = load_hidden_size(args.model_path) processor = load_processor(args.model_path) report = { "mode": args.mode, "model_path": args.model_path, "hidden_size": hidden_size, "save_dtype": args.save_dtype, "groups": [], } group_progress = tqdm( pairs, total=len(pairs), desc="Estimate groups", disable=not is_rank0(), leave=True, unit="group", ) for preset, task_name in group_progress: stats = estimate_group(preset, task_name, args, processor, hidden_size) report["groups"].append(stats) group_progress.set_postfix( source=preset.name, task=task_name, tib=f"{stats.get('estimated_total_tib', 0):.3f}", ) log( f"[ESTIMATE] {preset.name}/{task_name}: total={stats['total_items']:,} " f"avg_seq={stats.get('avg_seq_len', 0):.2f} avg_mb={stats.get('avg_output_mb', 0):.3f} " f"total_tib={stats.get('estimated_total_tib', 0):.3f}" ) group_progress.close() report_path = write_report(Path(args.output_root), args.mode, report) log(f"[REPORT] wrote {report_path}") def run_benchmark_or_export(args: argparse.Namespace, pairs: list[tuple[SourcePreset, str]]) -> None: maybe_init_distributed() device = current_device() save_dtype = save_dtype_from_arg(args.save_dtype) processor = load_processor(args.model_path) model = load_model(args.model_path, device, save_dtype) group_output_root = ( Path(args.output_root) / "_benchmark_outputs" if args.mode == "benchmark" else Path(args.output_root) ) report = { "mode": args.mode, "model_path": args.model_path, "world_size": world_size(), "rank": rank(), "save_dtype": args.save_dtype, "groups": [], } group_progress = tqdm( pairs, total=len(pairs), desc=f"{args.mode.title()} groups", disable=not is_rank0(), leave=True, unit="group", ) for preset, task_name in group_progress: stats = bench_or_export_group( preset, task_name, args, processor, model, device, save_dtype, group_output_root, ) if is_rank0(): report["groups"].append(stats) group_progress.set_postfix( source=preset.name, task=task_name, samples_per_sec=f"{stats['samples_per_sec']:.2f}", avg_mb=f"{stats['avg_output_mb']:.3f}", ) log( f"[{args.mode.upper()}] {preset.name}/{task_name}: processed={stats['processed']:,} " f"written={stats['written']:,} avg_seq={stats['avg_seq_len']:.2f} " f"samples/s={stats['samples_per_sec']:.2f} tokens/s={stats['tokens_per_sec']:.2f} " f"avg_mb={stats['avg_output_mb']:.3f}" ) group_progress.close() if is_rank0(): report_path = write_report(Path(args.output_root), args.mode, report) log(f"[REPORT] wrote {report_path}") cleanup_distributed() def main() -> None: warnings.filterwarnings( "ignore", message="The image processor of type `Qwen2VLImageProcessor` is now loaded as a fast processor by default.*", ) warnings.filterwarnings( "ignore", message="Unrecognized keys in `rope_scaling` for 'rope_type'='default': .*", ) args = parse_args() tasks = parse_csv_list(args.tasks) sources = parse_csv_list(args.sources) unknown_tasks = [task for task in tasks if task not in SUPPORTED_TASKS] if unknown_tasks: raise ValueError(f"Unsupported tasks: {unknown_tasks}") unknown_sources = [source for source in sources if source not in SOURCE_PRESETS] if unknown_sources: raise ValueError(f"Unsupported sources: {unknown_sources}") pairs = source_task_pairs(tasks, sources) if not pairs: raise ValueError("No compatible source/task pairs selected") ensure_video_export_is_confirmed(args, pairs) output_root = Path(args.output_root) output_root.mkdir(parents=True, exist_ok=True) log(f"Mode: {args.mode}") log(f"Tasks: {','.join(tasks)}") log(f"Sources: {','.join(sources)}") log(f"Output root: {output_root}") if args.mode == "estimate": run_estimate(args, pairs) return run_benchmark_or_export(args, pairs) if __name__ == "__main__": main()
from __future__ import annotations
import argparse
import gc
import hashlib
import json
import math
import os
import time
import traceback
import warnings
from collections import deque
from concurrent.futures import FIRST_COMPLETED, Future, ThreadPoolExecutor, wait
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Iterable, Iterator
import numpy as np
import torch
import torch.distributed as dist
from safetensors.torch import save_file
from tqdm import tqdm
from transformers import AutoConfig, Qwen2_5OmniProcessor, Qwen2_5OmniThinkerForConditionalGeneration
from psi.data.seed.seed_audio_motion_dataset import _AUDIO_COMMAND_PROMPT_POOLS
from psi.data.seed.seed_video_motion_dataset import _VIDEO_MOTION_PROMPT_POOLS
OMNI_DEFAULT_SYSTEM_PROMPT = (
"You are Qwen, a virtual human developed by the Qwen Team, Alibaba Group, "
"capable of perceiving auditory and visual inputs, as well as generating text and speech."
)
SUPPORTED_TASKS = (
"audio_only",
"audio_command_text",
"audio_command_only",
"video_clip_text",
"video_clip_only",
)
@dataclass(frozen=True)
class SourcePreset:
name: str
modality: str
dataset_root: Path
manifest_path: Path
allowed_tasks: tuple[str, ...]
instruction_key: str = ""
audio_path_key: str = "audio_path"
video_path_key: str = "video_path"
video_embed_dir: Path | None = None
is_audio_dir_manifest: bool = False
SOURCE_PRESETS: dict[str, SourcePreset] = {
"2264_with_audio": SourcePreset(
name="2264_with_audio",
modality="audio",
dataset_root=Path("/cpfs01/thscc/sharestorage/AIGC-06-01/Hithink_VideoGen_Group/user_workspace/buwendong/videogen/2264_with_audio"),
manifest_path=Path("/cpfs01/thscc/sharestorage/AIGC-06-01/Hithink_VideoGen_Group/user_workspace/buwendong/videogen/2264_with_audio/metadata_audio_npy.jsonl"),
allowed_tasks=("audio_only",),
),
"psi0_dance_audio": SourcePreset(
name="psi0_dance_audio",
modality="audio",
dataset_root=Path("/cpfs01/thscc/sharestorage/AIGC-06-01/Hithink_VideoGen_Group/user_workspace/buwendong/user/code/dance_1723_video_psi0/dance_1723_video_10s"),
manifest_path=Path(
"/cpfs01/thscc/sharestorage/AIGC-06-01/Hithink_VideoGen_Group/user_workspace/buwendong/user/code/dance_1723_video_psi0/dance_1723_video_10s/metadata_audio_npy.jsonl"
),
allowed_tasks=("audio_only",),
),
"qwen3_tts_seed_audio_command": SourcePreset(
name="qwen3_tts_seed_audio_command",
modality="audio",
dataset_root=Path("/cpfs01/thscc/sharestorage/AIGC-06-01/Hithink_VideoGen_Group/user_workspace/buwendong/user/code/qwen3-tts"),
manifest_path=Path("/cpfs01/thscc/sharestorage/AIGC-06-01/Hithink_VideoGen_Group/user_workspace/buwendong/user/code/qwen3-tts/metadata_audio_npy.jsonl"),
allowed_tasks=("audio_command_text", "audio_command_only"),
instruction_key="content_short_description",
is_audio_dir_manifest=True,
),
"dance_1723_video_10s_clip50": SourcePreset(
name="dance_1723_video_10s_clip50",
modality="video_clip",
dataset_root=Path("/cpfs01/thscc/sharestorage/AIGC-06-01/Hithink_VideoGen_Group/user_workspace/yetinghong/videogen/psi0_video_clip_50f_dense_stride1_direct_full/dance_1723_video_10s"),
manifest_path=Path(
"/cpfs01/thscc/sharestorage/AIGC-06-01/Hithink_VideoGen_Group/user_workspace/yetinghong/videogen/psi0_video_clip_50f_dense_stride1_direct_full/dance_1723_video_10s/metadata.jsonl"
),
allowed_tasks=("video_clip_text", "video_clip_only"),
instruction_key="video_caption",
video_embed_dir=Path(
"/cpfs01/thscc/sharestorage/AIGC-06-01/Hithink_VideoGen_Group/user_workspace/yetinghong/videogen/psi0_video_clip_50f_dense_stride1_direct_full/dance_1723_video_10s/embeds"
),
),
"motion_example_0506_demo_clip50": SourcePreset(
name="motion_example_0506_demo_clip50",
modality="video_clip",
dataset_root=Path(
"/cpfs01/thscc/sharestorage/AIGC-06-01/Hithink_VideoGen_Group/user_workspace/yetinghong/videogen/psi0_video_clip_50f_dense_stride1_direct_full/motion_example_0506_demo"