Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / data / dit / wan_video.py: 98%
327 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
1# Copyright 2026 Huawei Technologies Co., Ltd
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ============================================================================
15"""Wan video Dataset transform and DiT batching utilities."""
17from __future__ import annotations
19import io
20import math
21from collections.abc import Callable, Mapping, Sequence
22from pathlib import Path
23from typing import Any
25import numpy as np
26import torch
27from PIL import Image
28from torchvision.transforms import InterpolationMode, functional
30from hyper_parallel.data.dataset_logging import get_dataset_logger
31from hyper_parallel.data.parallel import (
32 DataLoaderParallelContext,
33 create_dataloader_parallel_context,
34)
35from hyper_parallel.data.text.build_dataset import (
36 build_online_iterable_dataset,
37 build_online_text_mapping_dataset,
38)
40logger = get_dataset_logger(__name__)
43def _align_to_factor_remainder_floor(value: float, factor: int, remainder: int) -> int:
44 adjusted = value - remainder
45 return int(adjusted // factor) * factor + remainder
48def _align_to_factor_remainder_ceil(value: float, factor: int, remainder: int) -> int:
49 adjusted = value - remainder
50 return math.ceil(adjusted / factor) * factor + remainder
53def _calculate_frame_indices(
54 *,
55 total_frames: int,
56 video_fps: float,
57 fps: float,
58 frame_factor: int | None,
59 frame_factor_remainder: int,
60 min_frames: int | None,
61 max_frames: int | None,
62) -> tuple[list[int], int]:
63 """Compute the source frame indices one clip samples under the fps/frame constraints."""
64 if total_frames <= 0:
65 raise ValueError("video must contain at least one frame")
66 if frame_factor is not None and frame_factor <= 0:
67 raise ValueError("frame_factor must be positive")
69 target_frames = total_frames / max(video_fps, 1e-6) * fps
70 if min_frames is not None:
71 if frame_factor is not None:
72 min_frames = _align_to_factor_remainder_ceil(min_frames, frame_factor, frame_factor_remainder)
73 target_frames = max(min_frames, target_frames)
74 if max_frames is not None:
75 if frame_factor is not None:
76 max_frames = _align_to_factor_remainder_floor(max_frames, frame_factor, frame_factor_remainder)
77 target_frames = min(max_frames, target_frames)
78 if frame_factor is not None:
79 target_frames = _align_to_factor_remainder_floor(target_frames, frame_factor, frame_factor_remainder)
80 target_frames = max(target_frames, frame_factor_remainder or frame_factor)
81 target_frames = int(max(1, target_frames))
83 sample_count = min(target_frames, total_frames)
84 pad_count = max(0, target_frames - total_frames)
85 indices = np.linspace(0, total_frames - 1, sample_count).round().astype(int).tolist()
86 return indices, pad_count
89def _normalize_video_tensor(video: Any) -> torch.Tensor:
90 """Normalize one decoded video array into a float CHW tensor scaled to [0, 255]."""
91 if isinstance(video, np.ndarray):
92 video = torch.from_numpy(video)
93 if not torch.is_tensor(video):
94 raise TypeError(f"Expected decoded video tensor/array, got {type(video).__name__}")
95 if video.ndim == 3:
96 video = video.unsqueeze(0)
97 if video.ndim != 4:
98 raise ValueError(f"Video tensor must be 4D, got shape {tuple(video.shape)}")
99 if video.shape[1] in (1, 3):
100 return video
101 if video.shape[-1] in (1, 3):
102 return video.permute(0, 3, 1, 2)
103 raise ValueError(f"Could not infer channel dimension for video shape {tuple(video.shape)}")
106def _pil_frames_to_tensor(frames: Sequence[Image.Image]) -> torch.Tensor:
107 tensors = []
108 for frame in frames:
109 if frame.mode != "RGB":
110 frame = frame.convert("RGB")
111 tensors.append(torch.from_numpy(np.array(frame)).permute(2, 0, 1))
112 return torch.stack(tensors)
115def _sample_video(
116 video: torch.Tensor,
117 *,
118 video_fps: float,
119 fps: float,
120 frame_factor: int | None,
121 frame_factor_remainder: int,
122 min_frames: int | None,
123 max_frames: int | None,
124) -> torch.Tensor:
125 """Decode one video input and sample the configured frames from it."""
126 indices, pad_count = _calculate_frame_indices(
127 total_frames=int(video.shape[0]),
128 video_fps=video_fps,
129 fps=fps,
130 frame_factor=frame_factor,
131 frame_factor_remainder=frame_factor_remainder,
132 min_frames=min_frames,
133 max_frames=max_frames,
134 )
135 video = video[indices]
136 if pad_count:
137 video = torch.cat([video, video[-1:].expand(pad_count, -1, -1, -1)], dim=0)
138 return video
141def _smart_resize(
142 video: torch.Tensor,
143 *,
144 scale_factor: int | None = None,
145 video_min_pixels: int | None = None,
146 video_max_pixels: int | None = None,
147 max_ratio: int | None = None,
148 **kwargs: Any,
149) -> torch.Tensor:
150 """Pick output height and width that keep the aspect ratio within the model factor constraints."""
151 del kwargs
152 if video.ndim != 4:
153 raise ValueError(f"video must be 4-dim, but got {video.ndim}")
154 _, _, height, width = video.shape
156 if max_ratio is not None:
157 ratio = max(width, height) / min(width, height)
158 if ratio > max_ratio:
159 raise ValueError(f"absolute aspect ratio must be smaller than {max_ratio}, got {ratio}")
161 if scale_factor is not None:
162 h_bar = max(scale_factor, round(height / scale_factor) * scale_factor)
163 w_bar = max(scale_factor, round(width / scale_factor) * scale_factor)
164 else:
165 h_bar = height
166 w_bar = width
168 if video_max_pixels is not None and h_bar * w_bar > video_max_pixels:
169 beta = math.sqrt((height * width) / video_max_pixels)
170 if scale_factor is not None:
171 h_bar = math.floor(height / beta / scale_factor) * scale_factor
172 w_bar = math.floor(width / beta / scale_factor) * scale_factor
173 else:
174 h_bar = math.floor(height / beta)
175 w_bar = math.floor(width / beta)
177 if video_min_pixels is not None and h_bar * w_bar < video_min_pixels:
178 beta = math.sqrt(video_min_pixels / (height * width))
179 if scale_factor is not None:
180 h_bar = math.ceil(height * beta / scale_factor) * scale_factor
181 w_bar = math.ceil(width * beta / scale_factor) * scale_factor
182 else:
183 h_bar = math.ceil(height * beta)
184 w_bar = math.ceil(width * beta)
186 return functional.resize(
187 video,
188 [h_bar, w_bar],
189 interpolation=InterpolationMode.BICUBIC,
190 antialias=True,
191 ).float()
194def _apply_dynamic_video_max_pixels(frame_count: int, kwargs: Mapping[str, Any]) -> dict[str, Any]:
195 """Clamp the resize pixel budget against the per-frame cap for the requested frame count."""
196 video_total_pixels = kwargs.get("video_total_pixels")
197 if video_total_pixels is None or frame_count <= 0:
198 return dict(kwargs)
200 temporal_merge_factor = kwargs.get("frame_factor", 2) or 2
201 video_max_pixels = kwargs.get("video_max_pixels")
202 video_min_pixels = kwargs.get("video_min_pixels")
203 dynamic_max = video_total_pixels / frame_count * temporal_merge_factor
204 if video_max_pixels is not None:
205 dynamic_max = min(dynamic_max, video_max_pixels)
206 if video_min_pixels is not None:
207 dynamic_max = max(dynamic_max, video_min_pixels * 1.05)
208 updated = dict(kwargs)
209 updated["video_max_pixels"] = int(dynamic_max)
210 return updated
213def _load_video_with_torchcodec(video_input: Any, **kwargs: Any) -> tuple[torch.Tensor, float] | None:
214 """Decode one video through torchcodec; return the frame tensor and source fps."""
215 try:
216 from torchcodec.decoders import VideoDecoder # pylint: disable=import-outside-toplevel
217 except ImportError:
218 return None
219 try:
220 decoder = VideoDecoder(video_input, device="cpu", num_ffmpeg_threads=0)
221 metadata = decoder.metadata
222 total_frames = int(metadata.num_frames or 0)
223 if total_frames <= 0:
224 raise ValueError("torchcodec did not report a positive frame count")
225 video_fps = float(metadata.average_fps or kwargs.get("fps", 24.0))
226 indices, pad_count = _calculate_frame_indices(
227 total_frames=total_frames,
228 video_fps=video_fps,
229 fps=float(kwargs.get("fps", 24.0)),
230 frame_factor=kwargs.get("frame_factor"),
231 frame_factor_remainder=int(kwargs.get("frame_factor_remainder", 0)),
232 min_frames=kwargs.get("min_frames"),
233 max_frames=kwargs.get("max_frames"),
234 )
235 frame_count = len(indices) + pad_count
236 resize_kwargs = _apply_dynamic_video_max_pixels(frame_count, kwargs)
237 video = _smart_resize(_normalize_video_tensor(decoder.get_frames_at(indices).data), **resize_kwargs)
238 if pad_count:
239 video = torch.cat([video, video[-1:].expand(pad_count, -1, -1, -1)], dim=0)
240 return video, video_fps
241 except Exception as error: # pylint: disable=broad-exception-caught
242 logger.debug("torchcodec video decode failed: %s", error)
243 return None
246def _load_video_with_imageio(video_input: Any) -> tuple[torch.Tensor, float]:
247 try:
248 import imageio.v3 as iio # pylint: disable=import-outside-toplevel
249 except ImportError as exc:
250 raise RuntimeError("Decoding video paths/bytes requires torchcodec or imageio") from exc
251 source = io.BytesIO(video_input) if isinstance(video_input, (bytes, bytearray)) else video_input
252 frames = iio.imread(source, index=None)
253 return _normalize_video_tensor(frames), 24.0
256def _load_video(video_input: Any, *, data_dir: str | None = None, **kwargs: Any) -> torch.Tensor:
257 """Load one video input into a normalized frame tensor via torchcodec or imageio."""
258 if torch.is_tensor(video_input) or isinstance(video_input, np.ndarray):
259 video = _normalize_video_tensor(video_input)
260 video_fps = float(kwargs.get("source_fps", kwargs.get("fps", 24.0)))
261 elif isinstance(video_input, list):
262 if not video_input:
263 raise ValueError("video frame list is empty")
264 frames = []
265 for frame in video_input:
266 if isinstance(frame, (bytes, bytearray)):
267 frame = Image.open(io.BytesIO(frame)).convert("RGB")
268 frames.append(frame)
269 video = _pil_frames_to_tensor(frames)
270 video_fps = float(kwargs.get("source_fps", kwargs.get("fps", 24.0)))
271 elif isinstance(video_input, dict):
272 if "frames" in video_input:
273 frames = []
274 for frame in video_input["frames"]:
275 if isinstance(frame, (bytes, bytearray)):
276 frame = Image.open(io.BytesIO(frame)).convert("RGB")
277 frames.append(frame)
278 video = _pil_frames_to_tensor(frames)
279 video_fps = float(video_input.get("video_fps", kwargs.get("fps", 24.0)))
280 indices, pad_count = _calculate_frame_indices(
281 total_frames=int(video.shape[0]),
282 video_fps=video_fps,
283 fps=float(kwargs.get("fps", 24.0)),
284 frame_factor=kwargs.get("frame_factor"),
285 frame_factor_remainder=int(kwargs.get("frame_factor_remainder", 0)),
286 min_frames=kwargs.get("min_frames"),
287 max_frames=kwargs.get("max_frames"),
288 )
289 resize_kwargs = _apply_dynamic_video_max_pixels(len(indices) + pad_count, kwargs)
290 return _sample_video(
291 _smart_resize(video, **resize_kwargs),
292 video_fps=video_fps,
293 fps=float(kwargs.get("fps", 24.0)),
294 frame_factor=kwargs.get("frame_factor"),
295 frame_factor_remainder=int(kwargs.get("frame_factor_remainder", 0)),
296 min_frames=kwargs.get("min_frames"),
297 max_frames=kwargs.get("max_frames"),
298 )
299 if "video" not in video_input:
300 raise ValueError("video dict must contain 'video' or 'frames'")
301 video = _normalize_video_tensor(video_input["video"])
302 video_fps = float(video_input.get("video_fps", kwargs.get("fps", 24.0)))
303 else:
304 source = video_input
305 if isinstance(source, str):
306 if data_dir and not source.startswith(("http://", "https://")):
307 source = str(Path(data_dir) / source)
308 if source.startswith(("http://", "https://")):
309 import requests # pylint: disable=import-outside-toplevel
311 source = requests.get(source, timeout=120).content
312 decoded = _load_video_with_torchcodec(source, **kwargs)
313 if decoded is not None:
314 return decoded[0]
315 decoded = _load_video_with_imageio(source)
316 video, video_fps = decoded
318 indices, pad_count = _calculate_frame_indices(
319 total_frames=int(video.shape[0]),
320 video_fps=video_fps,
321 fps=float(kwargs.get("fps", 24.0)),
322 frame_factor=kwargs.get("frame_factor"),
323 frame_factor_remainder=int(kwargs.get("frame_factor_remainder", 0)),
324 min_frames=kwargs.get("min_frames"),
325 max_frames=kwargs.get("max_frames"),
326 )
327 resize_kwargs = _apply_dynamic_video_max_pixels(len(indices) + pad_count, kwargs)
328 return _sample_video(
329 _smart_resize(video, **resize_kwargs),
330 video_fps=video_fps,
331 fps=float(kwargs.get("fps", 24.0)),
332 frame_factor=kwargs.get("frame_factor"),
333 frame_factor_remainder=int(kwargs.get("frame_factor_remainder", 0)),
334 min_frames=kwargs.get("min_frames"),
335 max_frames=kwargs.get("max_frames"),
336 )
339def _load_image(image_input: Any, *, data_dir: str | None = None) -> Image.Image:
340 """Load one image input into a PIL image, resolving relative paths against data_dir."""
341 if isinstance(image_input, Image.Image):
342 return image_input.convert("RGB")
343 if torch.is_tensor(image_input):
344 frame = image_input
345 if frame.ndim == 3 and frame.shape[0] in (1, 3):
346 frame = frame.permute(1, 2, 0)
347 if frame.dtype.is_floating_point:
348 frame = (frame * (255.0 if frame.max() <= 1.0 else 1.0)).clamp(0, 255).to(torch.uint8)
349 return Image.fromarray(frame.cpu().numpy()).convert("RGB")
350 if isinstance(image_input, np.ndarray):
351 return Image.fromarray(image_input).convert("RGB")
352 if isinstance(image_input, (bytes, bytearray)):
353 return Image.open(io.BytesIO(image_input)).convert("RGB")
354 if isinstance(image_input, str):
355 source = image_input
356 if data_dir and not source.startswith(("http://", "https://")):
357 source = str(Path(data_dir) / source)
358 if source.startswith(("http://", "https://")):
359 import requests # pylint: disable=import-outside-toplevel
361 return Image.open(io.BytesIO(requests.get(source, timeout=120).content)).convert("RGB")
362 return Image.open(source).convert("RGB")
363 raise TypeError(f"Unsupported image input type {type(image_input).__name__}")
366def _first_available(mapping: Mapping[str, Any], keys: Sequence[str]) -> Any:
367 """Return the first non-empty candidate-key value of one raw record."""
368 for key in keys:
369 value = mapping.get(key)
370 if value is None:
371 continue
372 if isinstance(value, str) and value == "":
373 continue
374 if isinstance(value, Sequence) and not isinstance(value, (bytes, bytearray, str)) and len(value) == 0:
375 continue
376 if isinstance(value, Mapping) and len(value) == 0:
377 continue
378 if torch.is_tensor(value) and value.numel() == 0:
379 continue
380 if isinstance(value, np.ndarray) and value.size == 0:
381 continue
382 return value
383 return None
386class WanVideoTransform:
387 """Convert raw records into Wan online DiT samples."""
389 def __init__(
390 self,
391 *,
392 task: str = "t2v",
393 source_name: str | None = None,
394 data_dir: str | None = None,
395 fps: float = 24.0,
396 min_frames: int | None = None,
397 max_frames: int | None = 81,
398 frame_factor: int | None = None,
399 frame_factor_remainder: int = 0,
400 use_first_video_frame_as_image: bool = True,
401 prompt_keys: Sequence[str] = ("prompt", "text", "caption", "input", "inputs"),
402 video_keys: Sequence[str] = ("video_bytes", "video", "video_path", "target_video", "target_video_path"),
403 image_keys: Sequence[str] = (
404 "image", "image_bytes", "image_path", "input_image", "reference_image", "first_frame",
405 ),
406 **kwargs: Any,
407 ) -> None:
408 if task not in {"t2v", "i2v"}:
409 raise ValueError("WanVideoTransform task must be either 't2v' or 'i2v'")
410 self.task = task
411 self.source_name = source_name
412 self.data_dir = data_dir
413 self.kwargs = {
414 **kwargs,
415 "fps": fps,
416 "min_frames": min_frames,
417 "max_frames": max_frames,
418 "frame_factor": frame_factor,
419 "frame_factor_remainder": frame_factor_remainder,
420 }
421 self.use_first_video_frame_as_image = use_first_video_frame_as_image
422 self.prompt_keys = tuple(prompt_keys)
423 self.video_keys = tuple(video_keys)
424 self.image_keys = tuple(image_keys)
426 def is_valid_sample(self, sample: Mapping[str, Any]) -> bool:
427 """Return whether one source record holds a prompt and a video to build a sample from."""
428 # Mirrors the fields _preprocess requires, so a record that passes here never fails
429 # there; images stay optional because i2v falls back to the video's first frame.
430 prompt = _first_available(sample, self.prompt_keys)
431 if prompt is None:
432 return False
433 return _first_available(sample, self.video_keys) is not None
435 def _preprocess(self, example: Mapping[str, Any]) -> tuple[str, list[Any], list[Any]]:
436 """Extract the prompt, optional image, and video entries from one raw record."""
437 if (
438 self.source_name == "Tom-and-Jerry-VideoGeneration-Dataset"
439 and "prompt" in example
440 and "video_bytes" in example
441 ):
442 return str(example["prompt"]), [], [example["video_bytes"]]
444 prompt = _first_available(example, self.prompt_keys)
445 video = _first_available(example, self.video_keys)
446 image = _first_available(example, self.image_keys)
447 if prompt is None:
448 raise ValueError(f"Wan data requires one prompt key from {self.prompt_keys}")
449 if video is None:
450 raise ValueError(f"Wan data requires one video key from {self.video_keys}")
451 images = [] if image is None else [image]
452 return str(prompt), images, [video]
454 def __call__(self, example: Mapping[str, Any]) -> list[dict[str, Any]]:
455 prompt, images, videos = self._preprocess(example)
456 processed_videos = [
457 _load_video(video, data_dir=self.data_dir, **self.kwargs)
458 for video in videos
459 ]
460 processed_images = [
461 _load_image(image, data_dir=self.data_dir)
462 for image in images
463 ]
464 if self.task == "i2v" and not processed_images and self.use_first_video_frame_as_image:
465 processed_images = [_load_image(processed_videos[0][0])]
466 sample = {"inputs": prompt, "videos": processed_videos}
467 if self.task == "i2v":
468 sample["images"] = processed_images
469 return [sample]
472def build_wan_video_transform(**kwargs: Any) -> WanVideoTransform:
473 """YAML target for the Wan online video transform."""
474 return WanVideoTransform(**kwargs)
477def _build_dataloader_context(mesh_context: Any, data_config: Mapping[str, Any]) -> DataLoaderParallelContext | None:
478 if mesh_context is None:
479 return None
480 return create_dataloader_parallel_context(
481 mesh_context,
482 data_index_cache=bool(data_config.get("data_index_cache", False)),
483 shared_storage=not bool(data_config.get("no_shared_storage", False)),
484 )
487def build_wan_video_dataset(
488 *,
489 data_config: Mapping[str, Any],
490 data_path: str | Sequence[str] | None = None,
491 transform: Callable[[Any], Any] | None = None,
492 dataloader_context: DataLoaderParallelContext | None = None,
493 mesh_context: Any = None,
494 training_config: Any = None,
495 **kwargs: Any,
496) -> Any:
497 """Build an online HuggingFace video dataset and apply the Wan transform."""
498 del kwargs
499 dataset_config = dict(data_config)
500 has_data_path = bool(data_path)
501 if isinstance(data_path, str):
502 has_data_path = bool(data_path.strip())
503 if has_data_path and dataset_config.get("hf_dataset_name") is not None:
504 logger.warning(
505 "Wan dataset data_path is set; ignoring hf_dataset_name=%s and loading local data_path instead.",
506 dataset_config["hf_dataset_name"],
507 )
508 dataset_config["hf_dataset_name"] = None
509 training_seed = getattr(training_config, "seed", None)
510 dataset_config["random_seed"] = 42 if training_seed is None else int(training_seed)
511 if dataloader_context is None:
512 dataloader_context = _build_dataloader_context(mesh_context, dataset_config)
513 dataset_type = str(dataset_config.pop("dataset_type", "mapping"))
514 if dataset_type == "iterable":
515 return build_online_iterable_dataset(
516 data_config=dataset_config,
517 data_path=data_path,
518 transform=transform,
519 dataloader_context=dataloader_context,
520 mesh_context=mesh_context,
521 training_config=training_config,
522 )
523 if dataset_type != "mapping":
524 raise ValueError(
525 f"Unsupported Wan online dataset_type {dataset_type!r}; expected one of ['iterable', 'mapping']"
526 )
527 return build_online_text_mapping_dataset(
528 data_config=dataset_config,
529 data_path=data_path,
530 transform=transform,
531 training_config=training_config,
532 )
535def _normalize_model_sample(sample: Any) -> Mapping[str, Any]:
536 if isinstance(sample, Mapping):
537 return sample
538 if isinstance(sample, Sequence) and not isinstance(sample, (str, bytes)):
539 if len(sample) != 1 or not isinstance(sample[0], Mapping):
540 raise ValueError("Wan fixed micro-batches expect each source item to produce one mapping sample")
541 return sample[0]
542 raise ValueError("Wan DataLoader samples must be mappings")
545class DiTCollator:
546 """List-preserving collator for per-sample DiT tensors and raw media."""
548 def __call__(self, model_samples: Sequence[Any]) -> dict[str, Any]:
549 if not model_samples:
550 raise ValueError("DiT micro-batch must contain at least one sample")
551 samples = [_normalize_model_sample(sample) for sample in model_samples]
552 keys = []
553 for sample in samples:
554 for key in sample:
555 if key not in keys:
556 keys.append(key)
557 return {key: [sample.get(key) for sample in samples] for key in keys}
560def build_dit_collate_fn() -> DiTCollator:
561 """YAML target for DiT collation."""
562 return DiTCollator()
565class DiTBatch:
566 """Read one collated DiT micro-batch from the DataLoader iterator."""
568 def __init__(
569 self,
570 mesh_context: Any,
571 device: Any,
572 pp_shared_data: bool = False,
573 ) -> None:
574 del device
575 self.mesh_context = mesh_context
576 self.pp_shared_data = pp_shared_data
577 self._logged = False
579 def __call__(self, data_iterator: Any) -> dict[str, Any]:
580 if self.pp_shared_data:
581 raise NotImplementedError("Wan DiT get_batch does not yet support pipeline-parallel shared data")
582 batch = next(data_iterator)
583 if not self._logged:
584 logger.debug(
585 "Wan DiT get_batch active on dp_rank=%s, tp_rank=%s, cp_rank=%s",
586 getattr(self.mesh_context, "dp_rank", 0),
587 getattr(self.mesh_context, "tp_rank", 0),
588 getattr(self.mesh_context, "cp_rank", 0),
589 )
590 self._logged = True
591 return batch