BWM-Turbo / examples /wanvideo /model_inference /inference_engine.py
Jingkuan's picture
Import model files from HAOqiushui/BWM-Turbo on ModelScope
df354ca verified
Raw History Blame Contribute Delete
59 kB
""" 推理引擎:负责所有推理逻辑 包括:检查点管理、数据加载、视频生成 """ import json import os import time from dataclasses import dataclass from pathlib import Path from typing import Dict, List, Optional import numpy as np import torch from diffsynth.core import UnifiedDataset from diffsynth.pipelines.wan_video import WanVideoPipeline from diffsynth.pipelines.wan_video_data import ( WAN_INFERENCE_DATASET_NUM_FRAMES, build_wan_video_dataset, ) from inference_support import ( CheckpointPipelineManager, DistributedInferenceContext, SampleRecordsSyncPaths, VideoSaver, WanInferenceConfig, barrier, build_sample_records_sync_paths, broadcast_object, config_output_path, read_jsonl_records, resolve_optional_path, suppress_stdout_if, write_jsonl_records, ) SAMPLE_RECORDS_SYNC_POLL_SEC = 5.0 SAMPLE_RECORDS_SYNC_TIMEOUT_SEC = 24 * 60 * 60.0 WORLD_ARENA_SUMMARY_IMAGE_PREFIX = "images" TASK_LENGTH_BIN_CHUNK_KEEP_FRAMES = { "le_121": 16, "122_300": 32, } TASK_LENGTH_BIN_KEEP_ALL_FUTURE = "gt_300" def build_worldarena_episode_video_name(episode_index: int) -> str: return f"episode{int(episode_index)}.mp4" def build_worldarena_episode_image_path( episode_index: int, image_prefix: str = WORLD_ARENA_SUMMARY_IMAGE_PREFIX, ) -> str: return str(Path(image_prefix) / f"episode{int(episode_index)}.png") def build_worldarena_summary_rows( sample_records: List[Dict], videos_dir: Path, image_prefix: str = WORLD_ARENA_SUMMARY_IMAGE_PREFIX, expected_episode_count: Optional[int] = None, first_episode_index: Optional[int] = None, ) -> List[Dict]: resolved_videos_dir = Path(videos_dir).resolve() ordered_rows = sorted(sample_records, key=lambda row: int(row["episode_index"])) if not ordered_rows: raise ValueError("WorldArena summary requires at least one sample record.") resolved_expected_episode_count = ( len(ordered_rows) if expected_episode_count is None else int(expected_episode_count) ) if len(ordered_rows) != resolved_expected_episode_count: raise ValueError( "WorldArena summary expects " f"{resolved_expected_episode_count} sample records, got {len(ordered_rows)}." ) actual_episode_indices = [int(row["episode_index"]) for row in ordered_rows] seen_episode_indices = set() duplicate_episode_indices = [] for episode_index in actual_episode_indices: if ( episode_index in seen_episode_indices and episode_index not in duplicate_episode_indices ): duplicate_episode_indices.append(episode_index) seen_episode_indices.add(episode_index) if duplicate_episode_indices: raise ValueError( "WorldArena summary expects unique episode_index values, " f"got duplicates={duplicate_episode_indices[:5]}." ) if first_episode_index is not None: expected_first_episode_index = int(first_episode_index) expected_episode_indices = list( range( expected_first_episode_index, expected_first_episode_index + resolved_expected_episode_count, ) ) if actual_episode_indices != expected_episode_indices: expected_last_episode_index = expected_first_episode_index + resolved_expected_episode_count - 1 raise ValueError( "WorldArena summary expects contiguous episode_index values, " f"expected {expected_first_episode_index}..{expected_last_episode_index}, " f"got first={actual_episode_indices[:5]} last={actual_episode_indices[-5:]}" ) summary_rows: List[Dict] = [] for metadata_row in ordered_rows: episode_index = int(metadata_row["episode_index"]) prompt = metadata_row.get("prompt") if not isinstance(prompt, str) or not prompt.strip(): raise ValueError( f"WorldArena summary requires a non-empty prompt for episode_index={episode_index}." ) video_path = resolved_videos_dir / build_worldarena_episode_video_name(episode_index) if not video_path.is_file(): raise FileNotFoundError(f"WorldArena summary expected generated video: {video_path}") summary_rows.append( { "gt_path": str(video_path), "image": build_worldarena_episode_image_path( episode_index, image_prefix=image_prefix, ), "prompt": [prompt], } ) return summary_rows @dataclass(frozen=True) class InferenceSample: sample_index: int original_video: torch.Tensor action: Optional[object] prompt: Optional[str] prompt_emb: Optional[object] negative_prompt_emb: Optional[object] episode_index: int num_views: int total_frames: int input_height: int input_width: int task_length_bin: Optional[str] = None class InferenceEngine: """ 推理引擎:负责整个推理流程 核心流程: 1. 加载数据集并选择样本 2. 发现所有 checkpoint 3. 初始化 pipeline(只加载一次 VAE/CLIP/T5) 4. 遍历每个 checkpoint: - 更新 DiT/Action Encoder 权重 - 生成所有样本的视频 5. 输出总结报告 """ def __init__( self, config: WanInferenceConfig, logger, dist_context: Optional[DistributedInferenceContext] = None, ) -> None: self.config = config self.logger = logger self.dist_context = dist_context or DistributedInferenceContext() self.video_saver = VideoSaver( fps=config.fps, quality=config.quality, show_progress=False, ) self.pipeline_manager = CheckpointPipelineManager( config, logger, device=self.dist_context.device, verbose=self._is_main_process(), ) self.dataset: Optional[UnifiedDataset] = None self.pipeline: Optional[WanVideoPipeline] = None self.requested_sample_indices: List[int] = [] self.sample_indices: List[int] = [] self.checkpoints: List[Path] = [] self.total_checkpoint_runs: int = 0 self.num_views: Optional[int] = None self.generated_sample_records: List[Dict] = [] self.requested_sample_count: int = 0 self._progress_total: int = 0 self._progress_completed_base: int = 0 self._progress_completed_local: int = 0 self._progress_started_at: float = 0.0 self._progress_sync_paths: Optional[SampleRecordsSyncPaths] = None def run(self) -> None: try: self._prepare() with suppress_stdout_if(not self._is_main_process()): self.pipeline = self.pipeline_manager.initialize_pipeline(self.checkpoints) checkpoints_to_run: List[Optional[Path]] = self.checkpoints if self.checkpoints else [None] self.total_checkpoint_runs = len(checkpoints_to_run) summaries: List[Dict] = [] for ckpt_idx, checkpoint in enumerate(checkpoints_to_run, 1): summaries.append( self._process_checkpoint( checkpoint, ckpt_idx=ckpt_idx, total_checkpoints=self.total_checkpoint_runs, ) ) except Exception as exc: # pragma: no cover - runtime protection self.logger.error(f"Inference failed: {exc}", exc_info=True) raise def _prepare(self) -> None: self._validate_inference_modes() self._load_dataset() selected_sample_indices = self._resolve_requested_sample_indices(len(self.dataset)) self.requested_sample_indices = list(selected_sample_indices) self.requested_sample_count = len(selected_sample_indices) self.checkpoints = self.pipeline_manager.discover_checkpoints() if self._is_main_process(): self.logger.info("Total metadata samples: %s", len(self.dataset)) self.logger.info("Requested sample range: full metadata") if self.checkpoints: self.logger.info("Checkpoints to process: %s", len(self.checkpoints)) else: self.logger.info("Checkpoints to process: pretrained-only (1 run)") if self._skip_existing_videos_enabled(): self.logger.info("Existing output videos will be reused when present.") if self._is_worldarena_summary_mode(): self.logger.info( "WorldArena summary export enabled; output videos use episode{episode_index}.mp4 and summary.json will be written to the split directory." ) self.logger.info("") def _resolve_requested_sample_indices(self, dataset_size: int) -> List[int]: return list(range(dataset_size)) def _use_autoregressive_history_template_mode(self) -> bool: return ( int(getattr(self.config, "history_template_sampling", 0)) == 1 and int(getattr(self.config, "num_history_frames", 1)) > 1 ) def _chunk_keep_frames_enabled(self) -> bool: flag = int(getattr(self.config, "chunk_keep_frames", 0)) if flag not in (0, 1): raise ValueError( "`chunk_keep_frames` is now an enable switch; use 0 to disable it or 1 to enable task_length_bin mapping." ) return flag == 1 def _resolve_autoregressive_chunk_keep_frames( self, sample: InferenceSample, future_frames: int, ) -> Optional[int]: if not self._chunk_keep_frames_enabled(): return None task_length_bin = None if sample.task_length_bin is None else str(sample.task_length_bin).strip() if not task_length_bin: raise ValueError( "`chunk_keep_frames` is enabled, but metadata field `task_length_bin` is missing " f"for sample_index={sample.sample_index}, episode_index={sample.episode_index}." ) if task_length_bin == TASK_LENGTH_BIN_KEEP_ALL_FUTURE: keep_frames = int(future_frames) elif task_length_bin in TASK_LENGTH_BIN_CHUNK_KEEP_FRAMES: keep_frames = int(TASK_LENGTH_BIN_CHUNK_KEEP_FRAMES[task_length_bin]) else: valid_bins = sorted([*TASK_LENGTH_BIN_CHUNK_KEEP_FRAMES.keys(), TASK_LENGTH_BIN_KEEP_ALL_FUTURE]) raise ValueError( "`chunk_keep_frames` is enabled, but unsupported task_length_bin=" f"{task_length_bin!r} for sample_index={sample.sample_index}, " f"episode_index={sample.episode_index}. Expected one of {valid_bins}." ) if keep_frames < 1: raise ValueError(f"Resolved chunk keep frames must be >= 1, got {keep_frames}") if keep_frames > future_frames: raise ValueError( "Resolved chunk keep frames from task_length_bin must be <= " f"num_frames - num_history_frames ({future_frames}), got {keep_frames} " f"for task_length_bin={task_length_bin!r}." ) return keep_frames def _use_first_frame_only_rollout_mode(self) -> bool: return int(getattr(self.config, "first_frame_only_rollout", 0)) == 1 def _skip_existing_videos_enabled(self) -> bool: return int(getattr(self.config, "skip_existing_videos", 0)) == 1 def _use_dynamic_sample_scheduling(self) -> bool: return self.dist_context.enabled and int(self.dist_context.world_size) > 1 def _is_worldarena_summary_mode(self) -> bool: return ( self._use_first_frame_only_rollout_mode() and int(getattr(self.config, "worldarena_summary_export", 0)) == 1 ) def _validate_inference_modes(self) -> None: if self._use_first_frame_only_rollout_mode() or self._use_autoregressive_history_template_mode(): num_frames = int(getattr(self.config, "num_frames", WAN_INFERENCE_DATASET_NUM_FRAMES)) num_history_frames = int(getattr(self.config, "num_history_frames", 1)) if num_history_frames < 1: raise ValueError(f"`num_history_frames` must be >= 1, got {num_history_frames}") if num_frames <= num_history_frames: raise ValueError( f"Autoregressive rollout requires num_frames > num_history_frames, got {num_frames} and {num_history_frames}" ) self._chunk_keep_frames_enabled() def _load_dataset(self) -> None: if self._is_main_process(): self.logger.info("Loading dataset...") if "action" in self.config.data_file_keys: self.logger.info("Action stat path: %s", self.config.action_stat_path) if self._use_autoregressive_history_template_mode(): self.logger.info( "Autoregressive history-template inference enabled; overriding dataset history_template_sampling to 0 to load full episodes." ) if self._chunk_keep_frames_enabled(): self.logger.info( "Metadata-driven chunk keep mode enabled: task_length_bin le_121=16, 122_300=32, gt_300=all future frames." ) if self._use_first_frame_only_rollout_mode(): self.logger.info( "First-frame-only rollout enabled; dataset video loader will read frame 0 only." ) with suppress_stdout_if(not self._is_main_process()): spatial_division_factor = int(getattr(self.config, "spatial_division_factor", 16)) dataset_history_template_sampling = ( 0 if self._use_autoregressive_history_template_mode() else int(getattr(self.config, "history_template_sampling", 0)) ) self.dataset = build_wan_video_dataset( self.config.runtime, base_path=self.config.dataset_base_path, metadata_path=self.config.dataset_metadata_path, height=self.config.height, width=self.config.width, num_frames=int(getattr(self.config, "num_frames", WAN_INFERENCE_DATASET_NUM_FRAMES)), num_history_frames=int(getattr(self.config, "num_history_frames", 1)), repeat=1, resize_mode=self.config.resize_mode, max_pixels=self.config.max_pixels, data_file_keys=self.config.data_file_keys, dataset_num_frames=WAN_INFERENCE_DATASET_NUM_FRAMES, action_stat_path=self.config.action_stat_path, action_type=self.config.action_type, history_template_sampling=dataset_history_template_sampling, video_num_frames_override=1 if self._use_first_frame_only_rollout_mode() else None, height_division_factor=spatial_division_factor, width_division_factor=spatial_division_factor, ) def _process_checkpoint( self, checkpoint: Optional[Path], ckpt_idx: int, total_checkpoints: int, ) -> Dict: checkpoint_name = checkpoint.name if checkpoint is not None else "pretrained" if self._is_main_process(): self.logger.info("\n%s", "#" * 80) self.logger.info( "Processing checkpoint %s/%s: %s", ckpt_idx, total_checkpoints, checkpoint_name, ) self.logger.info("%s\n", "#" * 80) with suppress_stdout_if(not self._is_main_process()): self.pipeline_manager.update_checkpoint(checkpoint) output_dirs = self._create_output_dirs(checkpoint) sample_records_sync = self._build_sample_records_sync_paths(output_dirs["videos"]) self.generated_sample_records = [] self.sample_indices = self._resolve_checkpoint_sample_indices(output_dirs) self._generate_all_videos(output_dirs, sample_records_sync) merged_sample_records = self._finalize_sample_records(sample_records_sync) if self._is_worldarena_summary_mode(): self._write_worldarena_summary(output_dirs["videos"], merged_sample_records) barrier(self.dist_context) if self.dist_context.is_main_process: self.logger.info("\n%s", "=" * 60) self.logger.info("VIDEO GENERATION COMPLETED") self.logger.info("%s", "=" * 60) self.logger.info("Total videos: %s", len(merged_sample_records)) self.logger.info("%s\n", "=" * 60) return { "checkpoint": checkpoint_name, "output_dir": output_dirs["root"].resolve(), "num_videos": len(merged_sample_records) if self.dist_context.is_main_process else self._progress_completed_local, } def _create_output_dirs(self, checkpoint: Optional[Path]) -> Dict[str, Path]: output_dir_value = None config_dir_value = None if self.dist_context.is_main_process: explicit_output_dir = self.config.values.get("output_dir") default_output_dir = Path("Ckpt") / "pretrained" if checkpoint is None else checkpoint.parent if explicit_output_dir: output_dir_value = str(Path(explicit_output_dir).expanduser()) else: output_dir_value = str(default_output_dir) # 原始实现始终写到 checkpoint 目录,推理时会覆盖训练 config.json。 # 显式指定 output_dir 时将推理配置保存在输出目录中。 config_dir_value = output_dir_value if explicit_output_dir else str(default_output_dir) output_dir = Path(broadcast_object(self.dist_context, output_dir_value)) config_dir = Path(broadcast_object(self.dist_context, config_dir_value)) output_dir.mkdir(parents=True, exist_ok=True) config_dir.mkdir(parents=True, exist_ok=True) videos_dir_name = "videos" if self._use_first_frame_only_rollout_mode(): videos_dir_name = Path(self.config.metadata_path).stem videos_dir = output_dir / videos_dir_name videos_dir.mkdir(parents=True, exist_ok=True) config_path = config_output_path(config_dir) if self.dist_context.is_main_process: self._save_config(config_path) barrier(self.dist_context) if self._is_main_process(): self.logger.info("Output directory: %s\n", output_dir.resolve()) self.logger.info("Saved config: %s", config_path.resolve()) return {"root": output_dir, "videos": videos_dir, "config": config_path} def _save_config(self, config_path: Path) -> None: with config_path.open("w", encoding="utf-8") as f: payload = self.config.grouped_config or self.config.values json.dump(payload, f, indent=2, ensure_ascii=True) def _build_sample_records_sync_paths(self, videos_dir: Path) -> SampleRecordsSyncPaths: run_token = None if self._is_main_process(): run_token = f"sample_records_{time.time_ns()}_{os.getpid()}" run_token = str(broadcast_object(self.dist_context, run_token)) sync_paths = build_sample_records_sync_paths( videos_dir, run_token=run_token, rank=self.dist_context.rank, ) if self._is_main_process() and self.dist_context.enabled: self.logger.info("Sample-record sync dir: %s", sync_paths.sync_dir.resolve()) return sync_paths def _resolve_checkpoint_sample_indices(self, output_dirs: Dict[str, Path]) -> List[int]: if self._skip_existing_videos_enabled(): payload = self._resolve_pending_sample_payload(output_dirs) pending_sample_indices = [int(sample_idx) for sample_idx in payload["pending_sample_indices"]] existing_count = self.requested_sample_count - len(pending_sample_indices) if self._is_main_process(): self.logger.info("Existing videos found for current checkpoint: %s", existing_count) self.logger.info("Pending videos for current checkpoint: %s", len(pending_sample_indices)) if not pending_sample_indices: self.logger.info("No pending videos remain for this checkpoint.") else: pending_sample_indices = list(self.requested_sample_indices) existing_count = 0 if self._is_main_process(): self.logger.info("Pending videos for current checkpoint: %s", len(pending_sample_indices)) self._progress_total = self.requested_sample_count self._progress_completed_base = existing_count if self._use_dynamic_sample_scheduling(): self.logger.info( "Rank %s participating in dynamic scheduling for %s pending sample(s).", self.dist_context.rank, len(pending_sample_indices), ) return pending_sample_indices assigned_sample_indices = pending_sample_indices[self.dist_context.rank :: self.dist_context.world_size] self.logger.info( "Rank %s assigned %s pending sample(s) for current checkpoint.", self.dist_context.rank, len(assigned_sample_indices), ) return assigned_sample_indices def _resolve_pending_sample_payload(self, output_dirs: Dict[str, Path]) -> Dict[str, List]: payload = None if self._is_main_process(): payload = self._build_pending_sample_payload(output_dirs) payload = broadcast_object(self.dist_context, payload) if self._is_main_process(): self.generated_sample_records.extend(payload["skipped_existing_records"]) return payload def _build_pending_sample_payload(self, output_dirs: Dict[str, Path]) -> Dict[str, List]: pending_sample_indices: List[int] = [] skipped_existing_records: List[Dict] = [] videos_dir = output_dirs["videos"] for sample_idx in self.requested_sample_indices: metadata_row = self._get_metadata_row(sample_idx) episode_index = self._resolve_metadata_episode_index(metadata_row, sample_idx) output_path = self._resolve_output_video_path_for_values(sample_idx, episode_index, videos_dir) if output_path.is_file(): skipped_existing_records.append( self._build_sample_record( video_path=output_path, videos_root=videos_dir, prompt=metadata_row.get("prompt"), episode_index=episode_index, sample_index=sample_idx, status="skipped_existing", ) ) continue pending_sample_indices.append(sample_idx) return { "pending_sample_indices": pending_sample_indices, "skipped_existing_records": skipped_existing_records, } def _generate_all_videos( self, output_dirs: Dict[str, Path], sync_paths: SampleRecordsSyncPaths, ) -> None: self._progress_sync_paths = sync_paths self._start_total_progress() if self._use_dynamic_sample_scheduling(): self._prepare_dynamic_sample_queue(sync_paths) self._generate_all_videos_dynamic(output_dirs, sync_paths) else: self._generate_all_videos_static(output_dirs) self._report_total_progress() def _generate_all_videos_static(self, output_dirs: Dict[str, Path]) -> None: for sample_idx in self.sample_indices: raw_sample = self.dataset[sample_idx] sample = self._prepare_sample(sample_idx, raw_sample) self._generate_single_video(sample, output_dirs) self._progress_completed_local += 1 self._report_total_progress() def _generate_all_videos_dynamic( self, output_dirs: Dict[str, Path], sync_paths: SampleRecordsSyncPaths, ) -> None: while True: sample_idx = self._claim_pending_sample_index(sync_paths, self.sample_indices) if sample_idx is None: return raw_sample = self.dataset[sample_idx] sample = self._prepare_sample(sample_idx, raw_sample) self._generate_single_video(sample, output_dirs) self._mark_sample_completed(sync_paths, sample_idx) self._progress_completed_local += 1 self._report_total_progress() @staticmethod def _prepare_dynamic_sample_queue(sync_paths: SampleRecordsSyncPaths) -> None: sync_paths.claims_dir.mkdir(parents=True, exist_ok=True) sync_paths.done_samples_dir.mkdir(parents=True, exist_ok=True) def _claim_pending_sample_index( self, sync_paths: SampleRecordsSyncPaths, pending_sample_indices: List[int], ) -> Optional[int]: for sample_idx in pending_sample_indices: claim_path = self._sample_claim_path(sync_paths, sample_idx) if claim_path.exists(): continue try: self._write_claim_marker(claim_path, sample_idx) except FileExistsError: continue return int(sample_idx) return None def _mark_sample_completed(self, sync_paths: SampleRecordsSyncPaths, sample_idx: int) -> Path: done_path = self._sample_done_path(sync_paths, sample_idx) payload = { "sample_index": int(sample_idx), "rank": int(self.dist_context.rank), "pid": int(os.getpid()), "completed_at_ns": int(time.time_ns()), } self._write_sync_marker(done_path, f"{json.dumps(payload, ensure_ascii=True)}\n") return done_path def _write_claim_marker(self, claim_path: Path, sample_idx: int) -> None: claim_path.parent.mkdir(parents=True, exist_ok=True) payload = { "sample_index": int(sample_idx), "rank": int(self.dist_context.rank), "pid": int(os.getpid()), "claimed_at_ns": int(time.time_ns()), } with claim_path.open("x", encoding="utf-8") as file_handle: json.dump(payload, file_handle, ensure_ascii=True) file_handle.write("\n") @staticmethod def _sample_claim_path(sync_paths: SampleRecordsSyncPaths, sample_idx: int) -> Path: return sync_paths.claims_dir / f"sample_{int(sample_idx):06d}.claim" @staticmethod def _sample_done_path(sync_paths: SampleRecordsSyncPaths, sample_idx: int) -> Path: return sync_paths.done_samples_dir / f"sample_{int(sample_idx):06d}.done" def _prepare_sample(self, sample_idx: int, sample: Dict) -> InferenceSample: original_video = sample["video"] if not isinstance(original_video, torch.Tensor) or original_video.ndim != 5: raise TypeError( f"`sample['video']` must be torch.Tensor with shape (V,C,T,H,W), got {type(original_video)}" ) original_video = original_video.detach().cpu() action = sample.get("action") if getattr(self.pipeline, "action_injection_mode", "off") == "off": action = None episode_index = int(sample["episode_index"]) task_length_bin = sample.get("task_length_bin") if task_length_bin is not None: task_length_bin = str(task_length_bin) prompt = sample.get("prompt") prompt_emb = resolve_optional_path(sample.get("prompt_emb"), self.config.dataset_base_path) negative_prompt_emb = sample.get("negative_prompt_emb", self.config.negative_prompt_emb) negative_prompt_emb = resolve_optional_path(negative_prompt_emb, self.config.dataset_base_path) num_views = int(original_video.shape[0]) if self._use_first_frame_only_rollout_mode(): if action is None: raise ValueError( "First-frame-only rollout requires action conditioning, but `sample['action']` is missing." ) length_value = sample.get("length") if length_value is None: raise ValueError("First-frame-only rollout requires metadata field `length`.") meta_length = int(length_value) if meta_length < 1: raise ValueError(f"Invalid metadata length for rollout: {meta_length}") action_frames = self._get_action_frame_count(action) total_frames = min(meta_length, action_frames) if total_frames < 1: raise ValueError( f"Invalid effective rollout length: meta_length={meta_length}, action_frames={action_frames}" ) if action_frames < meta_length: self.logger.warning( "First-frame-only rollout truncated by action length: meta_length=%s, action_frames=%s, effective_frames=%s", meta_length, action_frames, total_frames, ) else: total_frames = int(original_video.shape[2]) input_height = int(original_video.shape[-2]) input_width = int(original_video.shape[-1]) if self.num_views is None: self.num_views = num_views elif self.num_views != num_views: self.logger.warning("Mixed num_views detected: %s -> %s", self.num_views, num_views) return InferenceSample( sample_index=int(sample_idx), original_video=original_video, action=action, prompt=prompt, prompt_emb=prompt_emb, negative_prompt_emb=negative_prompt_emb, episode_index=episode_index, task_length_bin=task_length_bin, num_views=num_views, total_frames=total_frames, input_height=input_height, input_width=input_width, ) def _generate_single_video( self, sample: InferenceSample, output_dirs: Dict[str, Path], ) -> None: output_path = self._resolve_output_video_path(sample, output_dirs["videos"]) if self._skip_existing_videos_enabled() and output_path.is_file(): if self._is_main_process(): self.logger.info("Skipping existing video: %s\n", output_path.resolve()) self._record_generated_sample( video_path=output_path, videos_root=output_dirs["videos"], prompt=sample.prompt, episode_index=sample.episode_index, sample_index=sample.sample_index, status="skipped_existing", ) return predicted_video = self._predict_video(sample) predicted_video = self._finalize_predicted_video(predicted_video, sample.total_frames) if self._use_first_frame_only_rollout_mode(): saved_path = self.video_saver.save_predicted_only( predicted_video, output_dirs["videos"], output_path.name, ) else: saved_path = self.video_saver.save_comparison( sample.original_video, predicted_video, output_dirs["videos"], output_path.name, length_mode="truncate_min", ) self._record_generated_sample( video_path=saved_path, videos_root=output_dirs["videos"], prompt=sample.prompt, episode_index=sample.episode_index, sample_index=sample.sample_index, status="generated", ) if self._is_main_process(): self.logger.info("Saved: %s\n", saved_path.resolve()) def _predict_video(self, sample: InferenceSample) -> torch.Tensor: if self._use_first_frame_only_rollout_mode() or self._use_autoregressive_history_template_mode(): return self._run_autoregressive_history_template_inference(sample) return self._run_chunked_inference(sample) def _run_single_pass_inference(self, sample: InferenceSample) -> torch.Tensor: history_frames = int(self.config.num_history_frames) action = self._trim_action(sample.action, sample.total_frames) infer_frames = self._align_num_frames(sample.total_frames) infer_action = self._slice_and_pad_action( action=action, start=0, target_frames=sample.total_frames, infer_frames=infer_frames, ) predicted_video = self._call_pipeline( sample, input_video=sample.original_video[:, :, :history_frames], action=infer_action, infer_frames=infer_frames, ) predicted_video = predicted_video.detach().cpu()[:, :, :sample.total_frames] return self._restore_history_frames(predicted_video, sample.original_video, history_frames) def _run_autoregressive_history_template_inference(self, sample: InferenceSample) -> torch.Tensor: history_frames = int(self.config.num_history_frames) chunk_size = int(self.config.num_frames) future_frames = chunk_size - history_frames first_frame_only = self._use_first_frame_only_rollout_mode() use_history_template = self._use_autoregressive_history_template_mode() if future_frames <= 0: raise ValueError( f"Autoregressive rollout requires num_frames > num_history_frames, got {chunk_size} and {history_frames}" ) resolved_chunk_keep_frames = self._resolve_autoregressive_chunk_keep_frames(sample, future_frames) use_fixed_keep_chunks = ( resolved_chunk_keep_frames is not None and int(sample.total_frames) >= int(chunk_size) ) chunk_keep_frames = resolved_chunk_keep_frames if use_fixed_keep_chunks else future_frames if use_fixed_keep_chunks: self.logger.info( "Using chunk keep frames=%s for sample_index=%s, episode_index=%s, task_length_bin=%s.", chunk_keep_frames, sample.sample_index, sample.episode_index, sample.task_length_bin, ) if int(sample.original_video.shape[2]) < 1: raise ValueError("Inference sample must contain at least one conditioning video frame.") if not first_frame_only and sample.total_frames < history_frames: raise ValueError( f"Sample has {sample.total_frames} frames, smaller than num_history_frames={history_frames}" ) action = self._trim_action(sample.action, sample.total_frames) if first_frame_only: generated_frames: List[torch.Tensor] = [sample.original_video[:, :, 0].clone()] else: generated_frames = [ sample.original_video[:, :, frame_idx].clone() for frame_idx in range(history_frames) ] chunk_idx = 0 while len(generated_frames) < sample.total_frames: future_start = len(generated_frames) remaining_future = sample.total_frames - future_start if use_fixed_keep_chunks: tail_aligned_chunk = remaining_future <= chunk_keep_frames chunk_future_start = sample.total_frames - future_frames if tail_aligned_chunk else future_start history_source_frame_count = chunk_future_start current_future = future_frames requested_frames = chunk_size infer_frames = self._align_num_frames(requested_frames) else: tail_aligned_chunk = False chunk_future_start = future_start history_source_frame_count = future_start current_future = min(future_frames, remaining_future) requested_frames = history_frames + current_future infer_frames = self._align_num_frames(requested_frames) history_indices = self._build_autoregressive_history_indices( history_source_frame_count, history_frames, pad_with_first_frame=first_frame_only, use_history_template=use_history_template, ) chunk_input_video = torch.stack( [generated_frames[index] for index in history_indices], dim=2, ) chunk_action = self._build_autoregressive_action_condition( action=action, history_indices=history_indices, future_start=chunk_future_start, future_count=current_future, infer_frames=infer_frames, ) chunk_seed = None if self.config.seed is None else int(self.config.seed) + chunk_idx chunk_video = self._call_pipeline( sample, input_video=chunk_input_video, action=chunk_action, infer_frames=infer_frames, seed=chunk_seed, use_history_condition_noise_in_inference=True, ) chunk_video = chunk_video.detach().cpu()[:, :, :infer_frames] future_video = chunk_video[:, :, history_frames:] if use_fixed_keep_chunks and tail_aligned_chunk: replace_start = chunk_future_start replace_count = min( sample.total_frames - replace_start, int(future_video.shape[2]), ) if replace_count <= 0: raise RuntimeError( "Autoregressive history-template inference produced no future frames for the final chunk." ) for frame_idx in range(replace_count): target_index = replace_start + frame_idx frame = future_video[:, :, frame_idx].clone() if target_index < len(generated_frames): generated_frames[target_index] = frame else: generated_frames.append(frame) else: append_target = chunk_keep_frames if use_fixed_keep_chunks else current_future append_count = min(append_target, int(future_video.shape[2])) if append_count <= 0: raise RuntimeError( "Autoregressive history-template inference produced no future frames for the current chunk." ) for frame_idx in range(append_count): generated_frames.append(future_video[:, :, frame_idx].clone()) chunk_idx += 1 return torch.stack(generated_frames, dim=2)[:, :, :sample.total_frames] def _run_chunked_inference(self, sample: InferenceSample) -> torch.Tensor: history_frames = int(self.config.num_history_frames) chunk_size = int(self.config.num_frames) chunk_stride = chunk_size - history_frames if chunk_stride <= 0: raise ValueError( f"Chunked inference requires num_frames > num_history_frames, got {chunk_size} and {history_frames}" ) action = self._trim_action(sample.action, sample.total_frames) chunk_starts = [0] while chunk_starts[-1] + chunk_stride + chunk_size <= sample.total_frames: chunk_starts.append(chunk_starts[-1] + chunk_stride) predicted_chunks: List[torch.Tensor] = [] last_input_video = sample.original_video[:, :, :history_frames] for chunk_idx, start in enumerate(chunk_starts): chunk_frames = min(chunk_size, sample.total_frames - start) infer_frames = self._align_num_frames(chunk_frames) chunk_action = self._slice_and_pad_action( action=action, start=start, target_frames=chunk_frames, infer_frames=infer_frames, ) chunk_input_video = last_input_video chunk_video = self._call_pipeline( sample, input_video=chunk_input_video, action=chunk_action, infer_frames=infer_frames, ) chunk_video = chunk_video.detach().cpu()[:, :, :chunk_frames] chunk_video = self._restore_history_frames(chunk_video, chunk_input_video, history_frames) if int(chunk_video.shape[2]) > 0: last_input_video = chunk_video[:, :, -history_frames:].contiguous() if chunk_idx > 0: chunk_video = chunk_video[:, :, history_frames:] if int(chunk_video.shape[2]) > 0: predicted_chunks.append(chunk_video) if predicted_chunks: return torch.cat(predicted_chunks, dim=2) return sample.original_video[:, :, :0] def _call_pipeline( self, sample: InferenceSample, *, input_video: torch.Tensor, action, infer_frames: int, seed=None, use_history_condition_noise_in_inference: bool = False, ) -> torch.Tensor: predicted_video = self.pipeline( prompt=sample.prompt, negative_prompt=self.config.negative_prompt, prompt_emb=sample.prompt_emb, negative_prompt_emb=sample.negative_prompt_emb, input_video=input_video, action=action, seed=self.config.seed if seed is None else seed, tiled=False, height=sample.input_height, width=sample.input_width, num_frames=infer_frames, num_history_frames=int(self.config.num_history_frames), cfg_scale=self.config.cfg_scale, num_inference_steps=self.config.num_inference_steps, use_history_condition_noise_in_inference=use_history_condition_noise_in_inference, progress_bar_cmd=self._noop_progress_bar, ) if not isinstance(predicted_video, torch.Tensor) or predicted_video.ndim != 5: raise TypeError(f"Pipeline output must be (V,C,T,H,W), got {type(predicted_video)}") return predicted_video def _finalize_predicted_video( self, predicted_video: torch.Tensor, expected_frames: int, ) -> torch.Tensor: pred_frames = int(predicted_video.shape[2]) if pred_frames > expected_frames: return predicted_video[:, :, :expected_frames] if pred_frames < expected_frames: self.logger.warning("Generated %s frames, expected %s", pred_frames, expected_frames) return predicted_video def _record_generated_sample( self, video_path: Path, videos_root: Path, prompt, episode_index: int, sample_index: int, status: str = "generated", ) -> None: self.generated_sample_records.append( self._build_sample_record( video_path=video_path, videos_root=videos_root, prompt=prompt, episode_index=episode_index, sample_index=sample_index, status=status, ) ) def _build_sample_record( self, video_path: Path, videos_root: Path, prompt, episode_index: int, sample_index: int, status: str = "generated", ) -> Dict: if prompt is None: raise ValueError("`prompt` must be a non-empty string for standalone metric evaluation.") resolved_video_path = video_path.resolve() resolved_videos_root = videos_root.resolve() try: video_relpath = str(resolved_video_path.relative_to(resolved_videos_root)) except ValueError: video_relpath = str(video_path.name) return { "video_path": str(resolved_video_path), "video_relpath": video_relpath, "prompt": str(prompt), "episode_index": int(episode_index), "sample_index": int(sample_index), "rank": int(self.dist_context.rank), "metadata_file": str(Path(self.config.metadata_path).resolve()), "status": str(status), } def _finalize_sample_records(self, sync_paths: SampleRecordsSyncPaths) -> List[Dict]: local_records = list(self.generated_sample_records) if not self.dist_context.enabled: merged_records = self._sort_sample_records(local_records) write_jsonl_records(sync_paths.final_records_path, merged_records) self.logger.info("Saved sample records: %s", sync_paths.final_records_path.resolve()) return merged_records self._write_sample_records_shard(sync_paths, local_records) self._write_sync_marker(sync_paths.done_path, "done\n") if not self.dist_context.is_main_process: self._wait_for_paths( [sync_paths.merged_marker_path], description="merged sample-record marker", ) return [] done_paths = [sync_paths.sync_dir / f"done_rank{rank:06d}" for rank in range(self.dist_context.world_size)] self._wait_for_paths(done_paths, description="sample-record completion markers") merged_records = self._merge_sample_record_shards(sync_paths) write_jsonl_records(sync_paths.final_records_path, merged_records) self._write_sync_marker(sync_paths.merged_marker_path, "merged\n") self.logger.info("Saved sample records: %s", sync_paths.final_records_path.resolve()) return merged_records @staticmethod def _sort_sample_records(records: List[Dict]) -> List[Dict]: return sorted( records, key=lambda record: ( int(record.get("sample_index", -1)), int(record.get("episode_index", -1)), str(record.get("video_path", "")), ), ) def _write_sample_records_shard( self, sync_paths: SampleRecordsSyncPaths, records: List[Dict], ) -> None: write_jsonl_records(sync_paths.shard_path, records) self.logger.info( "Rank %s wrote %s sample-record shard entries: %s", self.dist_context.rank, len(records), sync_paths.shard_path.resolve(), ) @staticmethod def _write_sync_marker(path: Path, content: str) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(content, encoding="utf-8") def _wait_for_paths(self, paths: List[Path], description: str) -> None: deadline = time.monotonic() + SAMPLE_RECORDS_SYNC_TIMEOUT_SEC pending_paths = [Path(path) for path in paths] while True: missing_paths = [path for path in pending_paths if not path.exists()] if not missing_paths: return if time.monotonic() >= deadline: missing_preview = ", ".join(str(path) for path in missing_paths[:3]) raise TimeoutError( f"Timed out waiting for {description}: missing {len(missing_paths)} path(s); sample={missing_preview}" ) time.sleep(SAMPLE_RECORDS_SYNC_POLL_SEC) def _merge_sample_record_shards(self, sync_paths: SampleRecordsSyncPaths) -> List[Dict]: merged_records: List[Dict] = [] for rank in range(self.dist_context.world_size): shard_path = sync_paths.sync_dir / f"sample_records_rank{rank:06d}.jsonl" merged_records.extend(read_jsonl_records(shard_path)) return self._sort_sample_records(merged_records) def _write_worldarena_summary(self, videos_dir: Path, sample_records: List[Dict]) -> Optional[Path]: if not self._is_worldarena_summary_mode() or not self._is_main_process(): return None summary_rows = build_worldarena_summary_rows( sample_records, videos_dir, expected_episode_count=self.requested_sample_count, ) for row, record in zip(summary_rows, sorted(sample_records, key=lambda item: int(item["episode_index"]))): metadata = self._get_metadata_row(int(record["sample_index"])) image_path = metadata["video"] if isinstance(image_path, (list, tuple)): image_path = image_path[0] if isinstance(image_path, dict): image_path = image_path["data"] row["image"] = str(Path(resolve_optional_path(image_path, self.config.resolved_data_base)).resolve()) summary_path = Path(videos_dir) / "summary.json" summary_path.parent.mkdir(parents=True, exist_ok=True) with summary_path.open("w", encoding="utf-8") as file_handle: json.dump(summary_rows, file_handle, ensure_ascii=True, indent=2) file_handle.write("\n") self.logger.info("Saved summary: %s", summary_path.resolve()) return summary_path def _start_total_progress(self) -> None: self._progress_completed_local = 0 self._progress_started_at = time.monotonic() self._report_total_progress() def _report_total_progress(self) -> None: if not self._is_main_process(): return now = time.monotonic() elapsed = max(0.0, now - self._progress_started_at) total = max(0, self._progress_total) completed = self._resolve_progress_completed() completed = min(max(0, completed), total) if total else 0 percent = (completed / total * 100.0) if total else 100.0 rate = completed / elapsed if elapsed > 0.0 else 0.0 if completed >= total: eta_text = "00:00:00" elif rate > 0.0: eta_text = self._format_duration((total - completed) / rate) else: eta_text = "unknown" print( "[progress] " f"samples={completed}/{total} ({percent:.1f}%) " f"elapsed={self._format_duration(elapsed)} " f"eta={eta_text} " f"rate={rate * 60.0:.2f} samples/min", flush=True, ) def _resolve_progress_completed(self) -> int: completed = int(self._progress_completed_base) if self._use_dynamic_sample_scheduling(): return completed + self._count_completed_sample_markers() return completed + int(self._progress_completed_local) def _count_completed_sample_markers(self) -> int: sync_paths = self._progress_sync_paths if sync_paths is None: return 0 done_dir = sync_paths.done_samples_dir if not done_dir.exists(): return 0 return sum(1 for path in done_dir.iterdir() if path.is_file()) @staticmethod def _format_duration(seconds: float) -> str: total_seconds = max(0, int(seconds)) hours, remainder = divmod(total_seconds, 3600) minutes, secs = divmod(remainder, 60) return f"{hours:02d}:{minutes:02d}:{secs:02d}" def _is_main_process(self) -> bool: return self.dist_context.is_main_process @staticmethod def _noop_progress_bar(iterable, *args, **kwargs): return iterable @staticmethod def _align_num_frames(num_frames: int) -> int: if (num_frames - 1) % 4 == 0: return num_frames return num_frames + (4 - ((num_frames - 1) % 4)) @staticmethod def _slice_and_pad_action(action, start: int, target_frames: int, infer_frames: int): if action is None: return None chunk_action = action[:, start : start + target_frames] current_frames = int(chunk_action.shape[1]) if current_frames >= infer_frames: return chunk_action[:, :infer_frames] if current_frames <= 0: return chunk_action pad_frames = infer_frames - current_frames if isinstance(chunk_action, torch.Tensor): pad = chunk_action[:, -1:, :].repeat(1, pad_frames, 1) return torch.cat([chunk_action, pad], dim=1) pad = np.repeat(chunk_action[:, -1:, :], repeats=pad_frames, axis=1) return np.concatenate([chunk_action, pad], axis=1) @staticmethod def _restore_history_frames( predicted_video: torch.Tensor, history_source: torch.Tensor, history_frames: int, ) -> torch.Tensor: history_to_copy = min( int(history_frames), int(predicted_video.shape[2]), int(history_source.shape[2]), ) if history_to_copy > 0: predicted_video[:, :, :history_to_copy] = history_source[:, :, :history_to_copy] return predicted_video @staticmethod def _build_autoregressive_history_indices( num_generated_frames: int, history_frames: int, *, pad_with_first_frame: bool = False, use_history_template: bool = True, ) -> List[int]: if history_frames <= 0: return [] if num_generated_frames <= 0: raise ValueError("Autoregressive history requires at least one generated frame.") if pad_with_first_frame and num_generated_frames < history_frames: padded_prefix = [0] * (history_frames - num_generated_frames) return padded_prefix + list(range(num_generated_frames)) if num_generated_frames < history_frames: raise ValueError( f"Need at least {history_frames} generated frames, got {num_generated_frames}" ) if history_frames == 1: return [num_generated_frames - 1] if not use_history_template: return list(range(num_generated_frames - history_frames, num_generated_frames)) return [0] + list(range(num_generated_frames - (history_frames - 1), num_generated_frames)) @staticmethod def _build_autoregressive_action_condition( action, *, history_indices: List[int], future_start: int, future_count: int, infer_frames: int, ): if action is None: return None history_action = action[:, history_indices, :] future_action = action[:, future_start : future_start + future_count, :] if isinstance(action, torch.Tensor): action_cond = torch.cat([history_action, future_action], dim=1) current_frames = int(action_cond.shape[1]) if current_frames < infer_frames: pad = action_cond[:, -1:, :].repeat(1, infer_frames - current_frames, 1) action_cond = torch.cat([action_cond, pad], dim=1) return action_cond action_cond = np.concatenate([history_action, future_action], axis=1) current_frames = int(action_cond.shape[1]) if current_frames < infer_frames: pad = np.repeat(action_cond[:, -1:, :], repeats=infer_frames - current_frames, axis=1) action_cond = np.concatenate([action_cond, pad], axis=1) return action_cond @staticmethod def _trim_action(action, total_frames: int): if action is None: return None return action[:, :total_frames] @staticmethod def _build_default_video_name(sample_index: int, episode_index: int) -> str: return f"video_s{int(sample_index):06d}_ep{int(episode_index)}.mp4" def _build_video_name(self, sample_index: int, episode_index: int) -> str: if self._is_worldarena_summary_mode(): return build_worldarena_episode_video_name(episode_index) return self._build_default_video_name(sample_index, episode_index) def _resolve_output_video_path(self, sample: InferenceSample, videos_dir: Path) -> Path: return self._resolve_output_video_path_for_values( sample.sample_index, sample.episode_index, videos_dir, ) def _resolve_output_video_path_for_values( self, sample_index: int, episode_index: int, videos_dir: Path, ) -> Path: return videos_dir / self._build_video_name(sample_index, episode_index) def _get_metadata_row(self, sample_index: int) -> Dict: if self.dataset is None or not hasattr(self.dataset, "data"): raise RuntimeError("Dataset metadata is unavailable before inference planning.") return self.dataset.data[sample_index] @staticmethod def _resolve_metadata_episode_index(metadata_row: Dict, sample_index: int) -> int: if "episode_index" not in metadata_row: raise KeyError(f"Metadata row for sample_index={sample_index} is missing `episode_index`.") return int(metadata_row["episode_index"]) @staticmethod def _get_action_frame_count(action) -> int: if action is None: return 0 if not hasattr(action, "shape") or len(action.shape) < 2: raise TypeError(f"Unsupported action object without frame dimension: {type(action)}") return int(action.shape[1])
"""
推理引擎:负责所有推理逻辑
包括:检查点管理、数据加载、视频生成
"""
import json
import os
import time
from dataclasses import dataclass
from pathlib import Path
from typing import Dict, List, Optional
import numpy as np
import torch
from diffsynth.core import UnifiedDataset
from diffsynth.pipelines.wan_video import WanVideoPipeline
from diffsynth.pipelines.wan_video_data import (
WAN_INFERENCE_DATASET_NUM_FRAMES,
build_wan_video_dataset,
)
from inference_support import (
CheckpointPipelineManager,
DistributedInferenceContext,
SampleRecordsSyncPaths,
VideoSaver,
WanInferenceConfig,
barrier,
build_sample_records_sync_paths,
broadcast_object,
config_output_path,
read_jsonl_records,
resolve_optional_path,
suppress_stdout_if,
write_jsonl_records,
)
SAMPLE_RECORDS_SYNC_POLL_SEC = 5.0
SAMPLE_RECORDS_SYNC_TIMEOUT_SEC = 24 * 60 * 60.0
WORLD_ARENA_SUMMARY_IMAGE_PREFIX = "images"
TASK_LENGTH_BIN_CHUNK_KEEP_FRAMES = {
"le_121": 16,
"122_300": 32,
}
TASK_LENGTH_BIN_KEEP_ALL_FUTURE = "gt_300"
def build_worldarena_episode_video_name(episode_index: int) -> str:
return f"episode{int(episode_index)}.mp4"
def build_worldarena_episode_image_path(
episode_index: int,
image_prefix: str = WORLD_ARENA_SUMMARY_IMAGE_PREFIX,
) -> str:
return str(Path(image_prefix) / f"episode{int(episode_index)}.png")
def build_worldarena_summary_rows(
sample_records: List[Dict],
videos_dir: Path,
image_prefix: str = WORLD_ARENA_SUMMARY_IMAGE_PREFIX,
expected_episode_count: Optional[int] = None,
first_episode_index: Optional[int] = None,
) -> List[Dict]:
resolved_videos_dir = Path(videos_dir).resolve()
ordered_rows = sorted(sample_records, key=lambda row: int(row["episode_index"]))
if not ordered_rows:
raise ValueError("WorldArena summary requires at least one sample record.")
resolved_expected_episode_count = (
len(ordered_rows)
if expected_episode_count is None
else int(expected_episode_count)
)
if len(ordered_rows) != resolved_expected_episode_count:
raise ValueError(
"WorldArena summary expects "
f"{resolved_expected_episode_count} sample records, got {len(ordered_rows)}."
)
actual_episode_indices = [int(row["episode_index"]) for row in ordered_rows]
seen_episode_indices = set()
duplicate_episode_indices = []
for episode_index in actual_episode_indices:
if (
episode_index in seen_episode_indices
and episode_index not in duplicate_episode_indices
):
duplicate_episode_indices.append(episode_index)
seen_episode_indices.add(episode_index)
if duplicate_episode_indices:
raise ValueError(
"WorldArena summary expects unique episode_index values, "
f"got duplicates={duplicate_episode_indices[:5]}."
)
if first_episode_index is not None:
expected_first_episode_index = int(first_episode_index)