Diff Coverage

Diff: origin/master...HEAD, staged and unstaged changes

Source File Diff Coverage (%) Missing Lines
hyper_parallel/components/checkpoint/hf_storage.py 100%  
hyper_parallel/components/checkpoint/load_groups.py 100%  
hyper_parallel/components/checkpoint/weight_conversion.py 100%  
hyper_parallel/core/distributed_checkpoint/standard_planner.py 0.0% 897
hyper_parallel/data/dit/__init__.py 100%  
hyper_parallel/data/dit/wan_video.py 23.2% 44-45,49-50,64-67,69-81,83-86,91-103,107-112,126,135-138,151-154,156-159,161-163,165-166,168-172,174-175,177-181,183-184,186,196-198,200-210,215-226,235-243,247-253,258-280,289-290,299-302,304-309,311-316,318,327-328,341-359,361-363,375,377,379,381,409,448,450,455-456,460,464-469,474,478-480,498-504,508-515,523-524,527,536-542,549-557,562,574-577,580-584,590-591
hyper_parallel/trainer/__init__.py 100%  
hyper_parallel/trainer/dit_trainer.py 0.0% 17,19-21,23-24,26-35,37,40-41,48-50,53-56,59-68,71-79,82,84-87,91,94,99-102,111-113,120,122-123,131,134,137,139-141,143-144,146-152,154-157,159,161-162,166-168,175-177,182,194-201,203,205-209,214,216-219,225-226,228,234-239,243-244,246,251-253,255,257-262,264,269-279,281,283-287,289-290,292-300,302-307,309,314-315,317,321-323,325,327-329,338-341,343-352,354-358,360-362,365
hyper_parallel/core/distributed_checkpoint/standard_planner.py
893
894
895
896
897
898
899
900
901
            # to merge at all. Entries without a planner-data path stay flat.
            if metadata.planner_data is not None and k in metadata.planner_data:
                set_element(state_dict, metadata.planner_data[k], v)
            else:
                state_dict[k] = v

        super().configure_planner(
            state_dict,
            metadata,
hyper_parallel/data/dit/wan_video.py
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
logger = get_dataset_logger(__name__)


def _align_to_factor_remainder_floor(value: float, factor: int, remainder: int) -> int:
    adjusted = value - remainder
    return int(adjusted // factor) * factor + remainder


def _align_to_factor_remainder_ceil(value: float, factor: int, remainder: int) -> int:
    adjusted = value - remainder
    return math.ceil(adjusted / factor) * factor + remainder


def _calculate_frame_indices(
    *,
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
    min_frames: int | None,
    max_frames: int | None,
) -> tuple[list[int], int]:
    """Compute the source frame indices one clip samples under the fps/frame constraints."""
    if total_frames <= 0:
        raise ValueError("video must contain at least one frame")
    if frame_factor is not None and frame_factor <= 0:
        raise ValueError("frame_factor must be positive")

    target_frames = total_frames / max(video_fps, 1e-6) * fps
    if min_frames is not None:
        if frame_factor is not None:
            min_frames = _align_to_factor_remainder_ceil(min_frames, frame_factor, frame_factor_remainder)
        target_frames = max(min_frames, target_frames)
    if max_frames is not None:
        if frame_factor is not None:
            max_frames = _align_to_factor_remainder_floor(max_frames, frame_factor, frame_factor_remainder)
        target_frames = min(max_frames, target_frames)
    if frame_factor is not None:
        target_frames = _align_to_factor_remainder_floor(target_frames, frame_factor, frame_factor_remainder)
        target_frames = max(target_frames, frame_factor_remainder or frame_factor)
    target_frames = int(max(1, target_frames))

    sample_count = min(target_frames, total_frames)
    pad_count = max(0, target_frames - total_frames)
    indices = np.linspace(0, total_frames - 1, sample_count).round().astype(int).tolist()
    return indices, pad_count


def _normalize_video_tensor(video: Any) -> torch.Tensor:
    """Normalize one decoded video array into a float CHW tensor scaled to [0, 255]."""
    if isinstance(video, np.ndarray):
        video = torch.from_numpy(video)
    if not torch.is_tensor(video):
        raise TypeError(f"Expected decoded video tensor/array, got {type(video).__name__}")
    if video.ndim == 3:
        video = video.unsqueeze(0)
    if video.ndim != 4:
        raise ValueError(f"Video tensor must be 4D, got shape {tuple(video.shape)}")
    if video.shape[1] in (1, 3):
        return video
    if video.shape[-1] in (1, 3):
        return video.permute(0, 3, 1, 2)
    raise ValueError(f"Could not infer channel dimension for video shape {tuple(video.shape)}")


def _pil_frames_to_tensor(frames: Sequence[Image.Image]) -> torch.Tensor:
    tensors = []
    for frame in frames:
        if frame.mode != "RGB":
            frame = frame.convert("RGB")
        tensors.append(torch.from_numpy(np.array(frame)).permute(2, 0, 1))
    return torch.stack(tensors)


def _sample_video(
    video: torch.Tensor,
122
123
124
125
126
127
128
129
130
    min_frames: int | None,
    max_frames: int | None,
) -> torch.Tensor:
    """Decode one video input and sample the configured frames from it."""
    indices, pad_count = _calculate_frame_indices(
        total_frames=int(video.shape[0]),
        video_fps=video_fps,
        fps=fps,
        frame_factor=frame_factor,
131
132
133
134
135
136
137
138
139
140
141
142
        frame_factor_remainder=frame_factor_remainder,
        min_frames=min_frames,
        max_frames=max_frames,
    )
    video = video[indices]
    if pad_count:
        video = torch.cat([video, video[-1:].expand(pad_count, -1, -1, -1)], dim=0)
    return video


def _smart_resize(
    video: torch.Tensor,
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
    max_ratio: int | None = None,
    **kwargs: Any,
) -> torch.Tensor:
    """Pick output height and width that keep the aspect ratio within the model factor constraints."""
    del kwargs
    if video.ndim != 4:
        raise ValueError(f"video must be 4-dim, but got {video.ndim}")
    _, _, height, width = video.shape

    if max_ratio is not None:
        ratio = max(width, height) / min(width, height)
        if ratio > max_ratio:
            raise ValueError(f"absolute aspect ratio must be smaller than {max_ratio}, got {ratio}")

    if scale_factor is not None:
        h_bar = max(scale_factor, round(height / scale_factor) * scale_factor)
        w_bar = max(scale_factor, round(width / scale_factor) * scale_factor)
    else:
        h_bar = height
        w_bar = width

    if video_max_pixels is not None and h_bar * w_bar > video_max_pixels:
        beta = math.sqrt((height * width) / video_max_pixels)
        if scale_factor is not None:
            h_bar = math.floor(height / beta / scale_factor) * scale_factor
            w_bar = math.floor(width / beta / scale_factor) * scale_factor
        else:
            h_bar = math.floor(height / beta)
            w_bar = math.floor(width / beta)

    if video_min_pixels is not None and h_bar * w_bar < video_min_pixels:
        beta = math.sqrt(video_min_pixels / (height * width))
        if scale_factor is not None:
            h_bar = math.ceil(height * beta / scale_factor) * scale_factor
            w_bar = math.ceil(width * beta / scale_factor) * scale_factor
        else:
            h_bar = math.ceil(height * beta)
            w_bar = math.ceil(width * beta)

    return functional.resize(
        video,
        [h_bar, w_bar],
        interpolation=InterpolationMode.BICUBIC,
        antialias=True,
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230


def _apply_dynamic_video_max_pixels(frame_count: int, kwargs: Mapping[str, Any]) -> dict[str, Any]:
    """Clamp the resize pixel budget against the per-frame cap for the requested frame count."""
    video_total_pixels = kwargs.get("video_total_pixels")
    if video_total_pixels is None or frame_count <= 0:
        return dict(kwargs)

    temporal_merge_factor = kwargs.get("frame_factor", 2) or 2
    video_max_pixels = kwargs.get("video_max_pixels")
    video_min_pixels = kwargs.get("video_min_pixels")
    dynamic_max = video_total_pixels / frame_count * temporal_merge_factor
    if video_max_pixels is not None:
        dynamic_max = min(dynamic_max, video_max_pixels)
    if video_min_pixels is not None:
        dynamic_max = max(dynamic_max, video_min_pixels * 1.05)
    updated = dict(kwargs)
    updated["video_max_pixels"] = int(dynamic_max)
    return updated


def _load_video_with_torchcodec(video_input: Any, **kwargs: Any) -> tuple[torch.Tensor, float] | None:
    """Decode one video through torchcodec; return the frame tensor and source fps."""
    try:
        from torchcodec.decoders import VideoDecoder  # pylint: disable=import-outside-toplevel
    except ImportError:
        return None
    try:
        decoder = VideoDecoder(video_input, device="cpu", num_ffmpeg_threads=0)
        metadata = decoder.metadata
        total_frames = int(metadata.num_frames or 0)
        if total_frames <= 0:
            raise ValueError("torchcodec did not report a positive frame count")
        video_fps = float(metadata.average_fps or kwargs.get("fps", 24.0))
        indices, pad_count = _calculate_frame_indices(
            total_frames=total_frames,
            video_fps=video_fps,
            fps=float(kwargs.get("fps", 24.0)),
            frame_factor=kwargs.get("frame_factor"),
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
            frame_factor_remainder=int(kwargs.get("frame_factor_remainder", 0)),
            min_frames=kwargs.get("min_frames"),
            max_frames=kwargs.get("max_frames"),
        )
        frame_count = len(indices) + pad_count
        resize_kwargs = _apply_dynamic_video_max_pixels(frame_count, kwargs)
        video = _smart_resize(_normalize_video_tensor(decoder.get_frames_at(indices).data), **resize_kwargs)
        if pad_count:
            video = torch.cat([video, video[-1:].expand(pad_count, -1, -1, -1)], dim=0)
        return video, video_fps
    except Exception as error:  # pylint: disable=broad-exception-caught
        logger.debug("torchcodec video decode failed: %s", error)
        return None


def _load_video_with_imageio(video_input: Any) -> tuple[torch.Tensor, float]:
    try:
        import imageio.v3 as iio  # pylint: disable=import-outside-toplevel
    except ImportError as exc:
        raise RuntimeError("Decoding video paths/bytes requires torchcodec or imageio") from exc
    source = io.BytesIO(video_input) if isinstance(video_input, (bytes, bytearray)) else video_input
    frames = iio.imread(source, index=None)
    return _normalize_video_tensor(frames), 24.0


def _load_video(video_input: Any, *, data_dir: str | None = None, **kwargs: Any) -> torch.Tensor:
    """Load one video input into a normalized frame tensor via torchcodec or imageio."""
    if torch.is_tensor(video_input) or isinstance(video_input, np.ndarray):
        video = _normalize_video_tensor(video_input)
        video_fps = float(kwargs.get("source_fps", kwargs.get("fps", 24.0)))
    elif isinstance(video_input, list):
        if not video_input:
            raise ValueError("video frame list is empty")
        frames = []
        for frame in video_input:
            if isinstance(frame, (bytes, bytearray)):
                frame = Image.open(io.BytesIO(frame)).convert("RGB")
            frames.append(frame)
        video = _pil_frames_to_tensor(frames)
        video_fps = float(kwargs.get("source_fps", kwargs.get("fps", 24.0)))
    elif isinstance(video_input, dict):
        if "frames" in video_input:
            frames = []
            for frame in video_input["frames"]:
                if isinstance(frame, (bytes, bytearray)):
                    frame = Image.open(io.BytesIO(frame)).convert("RGB")
                frames.append(frame)
            video = _pil_frames_to_tensor(frames)
            video_fps = float(video_input.get("video_fps", kwargs.get("fps", 24.0)))
            indices, pad_count = _calculate_frame_indices(
                total_frames=int(video.shape[0]),
                video_fps=video_fps,
                fps=float(kwargs.get("fps", 24.0)),
                frame_factor=kwargs.get("frame_factor"),
285
286
287
288
289
290
291
292
293
294
                frame_factor_remainder=int(kwargs.get("frame_factor_remainder", 0)),
                min_frames=kwargs.get("min_frames"),
                max_frames=kwargs.get("max_frames"),
            )
            resize_kwargs = _apply_dynamic_video_max_pixels(len(indices) + pad_count, kwargs)
            return _sample_video(
                _smart_resize(video, **resize_kwargs),
                video_fps=video_fps,
                fps=float(kwargs.get("fps", 24.0)),
                frame_factor=kwargs.get("frame_factor"),
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
                frame_factor_remainder=int(kwargs.get("frame_factor_remainder", 0)),
                min_frames=kwargs.get("min_frames"),
                max_frames=kwargs.get("max_frames"),
            )
        if "video" not in video_input:
            raise ValueError("video dict must contain 'video' or 'frames'")
        video = _normalize_video_tensor(video_input["video"])
        video_fps = float(video_input.get("video_fps", kwargs.get("fps", 24.0)))
    else:
        source = video_input
        if isinstance(source, str):
            if data_dir and not source.startswith(("http://", "https://")):
                source = str(Path(data_dir) / source)
            if source.startswith(("http://", "https://")):
                import requests  # pylint: disable=import-outside-toplevel

                source = requests.get(source, timeout=120).content
        decoded = _load_video_with_torchcodec(source, **kwargs)
        if decoded is not None:
            return decoded[0]
        decoded = _load_video_with_imageio(source)
        video, video_fps = decoded

    indices, pad_count = _calculate_frame_indices(
        total_frames=int(video.shape[0]),
        video_fps=video_fps,
        fps=float(kwargs.get("fps", 24.0)),
        frame_factor=kwargs.get("frame_factor"),
323
324
325
326
327
328
329
330
331
332
        frame_factor_remainder=int(kwargs.get("frame_factor_remainder", 0)),
        min_frames=kwargs.get("min_frames"),
        max_frames=kwargs.get("max_frames"),
    )
    resize_kwargs = _apply_dynamic_video_max_pixels(len(indices) + pad_count, kwargs)
    return _sample_video(
        _smart_resize(video, **resize_kwargs),
        video_fps=video_fps,
        fps=float(kwargs.get("fps", 24.0)),
        frame_factor=kwargs.get("frame_factor"),
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367


def _load_image(image_input: Any, *, data_dir: str | None = None) -> Image.Image:
    """Load one image input into a PIL image, resolving relative paths against data_dir."""
    if isinstance(image_input, Image.Image):
        return image_input.convert("RGB")
    if torch.is_tensor(image_input):
        frame = image_input
        if frame.ndim == 3 and frame.shape[0] in (1, 3):
            frame = frame.permute(1, 2, 0)
        if frame.dtype.is_floating_point:
            frame = (frame * (255.0 if frame.max() <= 1.0 else 1.0)).clamp(0, 255).to(torch.uint8)
        return Image.fromarray(frame.cpu().numpy()).convert("RGB")
    if isinstance(image_input, np.ndarray):
        return Image.fromarray(image_input).convert("RGB")
    if isinstance(image_input, (bytes, bytearray)):
        return Image.open(io.BytesIO(image_input)).convert("RGB")
    if isinstance(image_input, str):
        source = image_input
        if data_dir and not source.startswith(("http://", "https://")):
            source = str(Path(data_dir) / source)
        if source.startswith(("http://", "https://")):
            import requests  # pylint: disable=import-outside-toplevel

            return Image.open(io.BytesIO(requests.get(source, timeout=120).content)).convert("RGB")
        return Image.open(source).convert("RGB")
    raise TypeError(f"Unsupported image input type {type(image_input).__name__}")


def _first_available(mapping: Mapping[str, Any], keys: Sequence[str]) -> Any:
    """Return the first non-empty candidate-key value of one raw record."""
371
372
373
374
375
376
377
378
379
380
381
382
383
384
            continue
        if isinstance(value, str) and value == "":
            continue
        if isinstance(value, Sequence) and not isinstance(value, (bytes, bytearray, str)) and len(value) == 0:
            continue
        if isinstance(value, Mapping) and len(value) == 0:
            continue
        if torch.is_tensor(value) and value.numel() == 0:
            continue
        if isinstance(value, np.ndarray) and value.size == 0:
            continue
        return value
    return None

405
406
407
408
409
410
411
412
413
        ),
        **kwargs: Any,
    ) -> None:
        if task not in {"t2v", "i2v"}:
            raise ValueError("WanVideoTransform task must be either 't2v' or 'i2v'")
        self.task = task
        self.source_name = source_name
        self.data_dir = data_dir
        self.kwargs = {
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
        prompt = _first_available(example, self.prompt_keys)
        video = _first_available(example, self.video_keys)
        image = _first_available(example, self.image_keys)
        if prompt is None:
            raise ValueError(f"Wan data requires one prompt key from {self.prompt_keys}")
        if video is None:
            raise ValueError(f"Wan data requires one video key from {self.video_keys}")
        images = [] if image is None else [image]
        return str(prompt), images, [video]

    def __call__(self, example: Mapping[str, Any]) -> list[dict[str, Any]]:
        prompt, images, videos = self._preprocess(example)
        processed_videos = [
            _load_video(video, data_dir=self.data_dir, **self.kwargs)
            for video in videos
        ]
        processed_images = [
            _load_image(image, data_dir=self.data_dir)
            for image in images
        ]
        if self.task == "i2v" and not processed_images and self.use_first_video_frame_as_image:
            processed_images = [_load_image(processed_videos[0][0])]
        sample = {"inputs": prompt, "videos": processed_videos}
        if self.task == "i2v":
            sample["images"] = processed_images
        return [sample]


def build_wan_video_transform(**kwargs: Any) -> WanVideoTransform:
    """YAML target for the Wan online video transform."""
    return WanVideoTransform(**kwargs)


def _build_dataloader_context(mesh_context: Any, data_config: Mapping[str, Any]) -> DataLoaderParallelContext | None:
    if mesh_context is None:
        return None
    return create_dataloader_parallel_context(
        mesh_context,
        data_index_cache=bool(data_config.get("data_index_cache", False)),
        shared_storage=not bool(data_config.get("no_shared_storage", False)),
    )
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
    training_config: Any = None,
    **kwargs: Any,
) -> Any:
    """Build an online HuggingFace video dataset and apply the Wan transform."""
    del kwargs
    dataset_config = dict(data_config)
    has_data_path = bool(data_path)
    if isinstance(data_path, str):
        has_data_path = bool(data_path.strip())
    if has_data_path and dataset_config.get("hf_dataset_name") is not None:
        logger.warning(
            "Wan dataset data_path is set; ignoring hf_dataset_name=%s and loading local data_path instead.",
            dataset_config["hf_dataset_name"],
        )
        dataset_config["hf_dataset_name"] = None
    training_seed = getattr(training_config, "seed", None)
    dataset_config["random_seed"] = 42 if training_seed is None else int(training_seed)
    if dataloader_context is None:
        dataloader_context = _build_dataloader_context(mesh_context, dataset_config)
    dataset_type = str(dataset_config.pop("dataset_type", "mapping"))
    if dataset_type == "iterable":
        return build_online_iterable_dataset(
            data_config=dataset_config,
            data_path=data_path,
            transform=transform,
            dataloader_context=dataloader_context,
519
520
521
522
523
524
525
526
527
528
529
530
531
            dataloader_context=dataloader_context,
            mesh_context=mesh_context,
            training_config=training_config,
        )
    if dataset_type != "mapping":
        raise ValueError(
            f"Unsupported Wan online dataset_type {dataset_type!r}; expected one of ['iterable', 'mapping']"
        )
    return build_online_text_mapping_dataset(
        data_config=dataset_config,
        data_path=data_path,
        transform=transform,
        training_config=training_config,
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
    )


def _normalize_model_sample(sample: Any) -> Mapping[str, Any]:
    if isinstance(sample, Mapping):
        return sample
    if isinstance(sample, Sequence) and not isinstance(sample, (str, bytes)):
        if len(sample) != 1 or not isinstance(sample[0], Mapping):
            raise ValueError("Wan fixed micro-batches expect each source item to produce one mapping sample")
        return sample[0]
    raise ValueError("Wan DataLoader samples must be mappings")


class DiTCollator:
    """List-preserving collator for per-sample DiT tensors and raw media."""
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
class DiTCollator:
    """List-preserving collator for per-sample DiT tensors and raw media."""

    def __call__(self, model_samples: Sequence[Any]) -> dict[str, Any]:
        if not model_samples:
            raise ValueError("DiT micro-batch must contain at least one sample")
        samples = [_normalize_model_sample(sample) for sample in model_samples]
        keys = []
        for sample in samples:
            for key in sample:
                if key not in keys:
                    keys.append(key)
        return {key: [sample.get(key) for sample in samples] for key in keys}


def build_dit_collate_fn() -> DiTCollator:
    """YAML target for DiT collation."""
    return DiTCollator()


class DiTBatch:
    """Read one collated DiT micro-batch from the DataLoader iterator."""
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
        mesh_context: Any,
        device: Any,
        pp_shared_data: bool = False,
    ) -> None:
        del device
        self.mesh_context = mesh_context
        self.pp_shared_data = pp_shared_data
        self._logged = False

    def __call__(self, data_iterator: Any) -> dict[str, Any]:
        if self.pp_shared_data:
            raise NotImplementedError("Wan DiT get_batch does not yet support pipeline-parallel shared data")
        batch = next(data_iterator)
        if not self._logged:
            logger.debug(
                "Wan DiT get_batch active on dp_rank=%s, tp_rank=%s, cp_rank=%s",
                getattr(self.mesh_context, "dp_rank", 0),
                getattr(self.mesh_context, "tp_rank", 0),
                getattr(self.mesh_context, "cp_rank", 0),
586
587
588
589
590
591
                getattr(self.mesh_context, "dp_rank", 0),
                getattr(self.mesh_context, "tp_rank", 0),
                getattr(self.mesh_context, "cp_rank", 0),
            )
            self._logged = True
        return batch
hyper_parallel/trainer/dit_trainer.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# limitations under the License.
# ============================================================================
"""DiT trainer assembled from the shared AutoModels BaseTrainer stages."""

from __future__ import annotations

import inspect
from collections import defaultdict
from typing import Any, Dict

import torch  # pylint: disable=forbidden-backend-import
import torch.nn.functional as F  # pylint: disable=forbidden-backend-import

from hyper_parallel import SkipDTensorDispatch
from hyper_parallel.core.utils import clip_grad_norm_
from hyper_parallel.data.batching import calculate_num_micro_batches
from hyper_parallel.data.dit import DiTBatch
from hyper_parallel.models._transformers import resolve_dit_provider
from hyper_parallel.trainer.base import BaseTrainer
from hyper_parallel.trainer.config import TrainerConfig
from hyper_parallel.trainer.runtime.device import synchronize
from hyper_parallel.trainer.runtime.logging import create_logger
from hyper_parallel.trainer.runtime.memory import empty_cache, print_device_mem_info

logger = create_logger(__name__)


def _is_rank0() -> bool:
    return (
        not torch.distributed.is_available()
        or not torch.distributed.is_initialized()
        or torch.distributed.get_rank() == 0
    )
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
        or torch.distributed.get_rank() == 0
    )


def _rank0_info(message: str, *args: Any) -> None:
    if _is_rank0():
        logger.info(message, *args)


def _as_float(value: Any) -> float:
    if isinstance(value, torch.Tensor):
        return value.item()
    return float(value)


def _move_nested_to_device(value: Any, device: torch.device) -> Any:
    if isinstance(value, torch.Tensor):
        return value.to(device, non_blocking=True)
    if isinstance(value, dict):
        return {key: _move_nested_to_device(item, device) for key, item in value.items()}
    if isinstance(value, list):
        return [_move_nested_to_device(item, device) for item in value]
    if isinstance(value, tuple):
        return tuple(_move_nested_to_device(item, device) for item in value)
    return value


def _count_parameters(module: torch.nn.Module) -> tuple[int, int]:
    total = 0
    trainable = 0
    for parameter in module.parameters():
        numel = parameter.numel()
        total += numel
        if parameter.requires_grad:
            trainable += numel
    return total, trainable


def _unwrap_single_sample(value: Any, field_name: str) -> Any:
    """Unwrap collator-preserved sample lists for an upstream DiT model."""
    if not isinstance(value, list):
        return value
    if len(value) != 1:
        raise ValueError(
            "Diffusers DiT training currently requires micro_batch_size=1; "
            f"field {field_name!r} contains {len(value)} samples"
        )
    return value[0]


def _select_forward_inputs(
    model: torch.nn.Module,
    micro_batch: dict[str, Any],
) -> dict[str, Any]:
    """Project a conditioned batch onto the upstream model's forward inputs."""
    signature = getattr(model, "_hp_forward_signature", None)
    if signature is None:
        signature = inspect.signature(inspect.unwrap(model.forward))
    accepted_names = {
        name
        for name, parameter in signature.parameters.items()
        if name != "self"
        and parameter.kind in (
107
108
109
110
111
112
113
114
115
116
117
            inspect.Parameter.POSITIONAL_OR_KEYWORD,
            inspect.Parameter.KEYWORD_ONLY,
        )
    }
    if any(parameter.kind is inspect.Parameter.VAR_KEYWORD for parameter in signature.parameters.values()):
        accepted_names = micro_batch.keys()
    return {
        name: _unwrap_single_sample(value, name)
        for name, value in micro_batch.items()
        if name in accepted_names
    }
116
117
118
119
120
121
122
123
124
125
126
127
        if name in accepted_names
    }


def _has_condition_inputs(condition_model: torch.nn.Module, micro_batch: dict[str, Any]) -> bool:
    """Return whether a batch provides the condition model's required inputs."""
    signature = inspect.signature(inspect.unwrap(condition_model.get_condition))
    required_names = {
        name
        for name, parameter in signature.parameters.items()
        if name != "self"
        and parameter.default is inspect.Parameter.empty
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
        and parameter.default is inspect.Parameter.empty
        and parameter.kind
        in (inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.KEYWORD_ONLY)
    }
    return required_names.issubset(micro_batch)


class DiTTrainer:
    """Compose DiT full-finetuning runtime from explicit BaseTrainer stages."""

    base: BaseTrainer

    def __init__(self, config: TrainerConfig) -> None:
        self.base = BaseTrainer.__new__(BaseTrainer)
        self.base.config = config

        self.base._setup()
        self.base._build_model()

        self._build_model_assets()
        self._build_data_transform()
        self.base._build_dataset()
        self._build_collate_fn()
        self.base._build_dataloader()
        self._build_get_batch()
        self.base._compute_train_iters()

        self.base._build_optimizer()
        self.base._build_lr_scheduler()
        self.base._build_training_context()
        self.base._init_callbacks()

    def _build_model_assets(self) -> None:
        """Resolve the DiT provider and build its condition model when one is provided."""
        config = self.base.config
        provider = resolve_dit_provider(
            getattr(config.model, "model_provider", None),
            getattr(config.model, "model_type", None),
        )
        build_condition = getattr(provider, "build_condition_model", None)
        if callable(build_condition):
            self.base.condition_model = build_condition(
                model_target=config.model,
                device=self.base.device,
                dp_rank=self.base.mesh.dp_rank,
                seed=self.base.config.training.seed or self.base.default_seed,
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
                dp_rank=self.base.mesh.dp_rank,
                seed=self.base.config.training.seed or self.base.default_seed,
            )
        else:
            self.base.condition_model = None
        model_total, model_trainable = _count_parameters(self.base.model)
        condition_total, condition_trainable = (
            _count_parameters(self.base.condition_model)
            if self.base.condition_model is not None
            else (0, 0)
        )
        _rank0_info(
            "DiT trainability: task=%s, transformer_path=%s, condition_path=%s, "
            "transformer_local_trainable=%d/%d, condition_trainable=%d/%d",
            getattr(config.model, "task", None),
            getattr(config.model, "pretrained_model_name_or_path", None),
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
            condition_trainable,
            condition_total,
        )

    def _build_data_transform(self) -> None:
        dataset_config = self.base.config.dataset
        if dataset_config is None:
            raise ValueError("dataset must define a build target")
        if dataset_config.data_transform is None:
            self.base.data_transform = None
            return
        self.base.data_transform = dataset_config.data_transform.build()

    def _build_collate_fn(self) -> None:
        """Build the collate function and derive the micro-batch count."""
        dataloader_config = self.base.config.dataloader
        if dataloader_config is None or dataloader_config.collate_fn is None:
            raise ValueError("dataloader.collate_fn must define a build target")
        training_config = self.base.config.training
        self.base.num_micro_batches = calculate_num_micro_batches(
            global_batch_size=training_config.global_batch_size,
            micro_batch_size=training_config.micro_batch_size,
            dp_world_size=self.base.mesh.dp_size,
        )
        self.base.collate_fn = dataloader_config.collate_fn.build()

    def _build_get_batch(self) -> None:
        config = self.base.config
        get_batch_builder = config.dataloader.get_batch.build if config.dataloader.get_batch else DiTBatch
        self.base.get_batch = get_batch_builder(
            mesh_context=self.base.mesh,
            device=self.base.device,
            pp_shared_data=bool(getattr(config.dataloader, "pp_shared_data", False)),
        )
221
222
223
224
225
226
227
228
229
230
231
232
            device=self.base.device,
            pp_shared_data=bool(getattr(config.dataloader, "pp_shared_data", False)),
        )

    def preforward(self, micro_batch: dict[str, Any]) -> dict[str, Any]:
        return {key: _move_nested_to_device(value, self.base.device) for key, value in micro_batch.items()}

    def postforward(
        self,
        outputs: Any,
        micro_batch: dict[str, Any],
    ) -> tuple[torch.Tensor, dict[str, torch.Tensor]]:
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
        outputs: Any,
        micro_batch: dict[str, Any],
    ) -> tuple[torch.Tensor, dict[str, torch.Tensor]]:
        """Compute the flow-matching objective outside the upstream model."""
        if "training_target" not in micro_batch:
            raise ValueError("Conditioned DiT batch missing required loss field: training_target")
        prediction = getattr(outputs, "sample", None)
        if not isinstance(prediction, torch.Tensor):
            raise ValueError("Diffusers DiT model output must contain a tensor in 'sample'")
        training_target = _unwrap_single_sample(
            micro_batch["training_target"],
            "training_target",
        )
        if not isinstance(training_target, torch.Tensor):
            raise ValueError("DiT training_target must be a tensor")

        mse_loss = F.mse_loss(
            prediction.float(),
            training_target.float(),
            reduction="none",
        )
        mse_loss = mse_loss.reshape(mse_loss.shape[0], -1).mean(dim=1).mean()
        scaled_loss = mse_loss / self.base.num_micro_batches
        return scaled_loss, {"mse_loss": scaled_loss}

    def forward_backward_step(self, micro_batch: dict[str, Any]) -> tuple[torch.Tensor, dict[str, torch.Tensor]]:
        """Run one conditioned forward-backward micro-batch and return the scaled loss."""
        micro_batch = self.preforward(micro_batch)
        condition_model = getattr(self.base, "condition_model", None)
        if condition_model is not None and _has_condition_inputs(condition_model, micro_batch):
            with torch.no_grad():
                micro_batch = condition_model.get_condition(**micro_batch)
                micro_batch = condition_model.process_condition(**micro_batch)

        model_fwd_context = (
            self.base.model_fwd_context()
            if callable(self.base.model_fwd_context)
            else self.base.model_fwd_context
        )
        with model_fwd_context:
            model_inputs = _select_forward_inputs(self.base.model, micro_batch)
            outputs = self.base.model(**model_inputs)
        loss, loss_dict = self.postforward(outputs, micro_batch)
        del outputs
        if self.base.config.training.empty_cache_before_backward:
            empty_cache()
        with self.base.model_bwd_context:
            loss.backward()
        del micro_batch
        return loss, loss_dict

    def train_step(self, data_iterator: Any) -> Dict[str, float]:
        """Consume micro-batches, accumulate gradients, and apply one optimizer update."""
        config = self.base.config
        num_micro_steps = self.base.num_micro_batches
        micro_batches = [self.base.get_batch(data_iterator)]
        for _ in range(1, num_micro_steps):
            micro_batches.append(self.base.get_batch(data_iterator))

        self.base.on_step_begin(micro_batches=micro_batches)
        synchronize()

        total_loss = 0.0
        total_loss_dict = defaultdict(float)
        for micro_step, micro_batch in enumerate(micro_batches):
            self.base.model_reshard(micro_step, num_micro_steps)
            self.base.configure_fsdp_gradient_sync(micro_step, num_micro_steps)
            loss, loss_dict = self.forward_backward_step(micro_batch)
            total_loss += _as_float(loss)
            for loss_name, loss_value in loss_dict.items():
                total_loss_dict[loss_name] += _as_float(loss_value)

        grad_norm = clip_grad_norm_(self.base.model, config.training.max_grad_norm)
        optimizers = self.base.optimizer if isinstance(self.base.optimizer, list) else [self.base.optimizer]
        for optimizer in optimizers:
            with SkipDTensorDispatch():
                optimizer.step()
            optimizer.zero_grad()

        schedulers = (
            self.base.lr_scheduler
            if isinstance(self.base.lr_scheduler, list)
            else ([self.base.lr_scheduler] if self.base.lr_scheduler is not None else [])
        )
        for scheduler in schedulers:
            scheduler.step()

        grad_norm_value = _as_float(grad_norm)
        # Checkpoint and logging callbacks must observe the number of completed
        # optimizer updates; otherwise step-based saves start at step 0 and
        # fire one update later than their configured cadence.
        self.base.state.global_step += 1
        self.base.on_step_end(loss=total_loss, loss_dict=total_loss_dict, grad_norm=grad_norm_value)
        return {"loss": total_loss, "grad_norm": grad_norm_value}

    def train(self) -> None:
        """Run the full training loop across epochs."""
        config = self.base.config
        self.base.on_train_begin()
        logger.info(
            "Rank%s Start DiT training. Global step: %s. Train iters: %s. Start epoch: %s. Train epochs: %s.",
            self.base.local_rank,
            self.base.state.global_step,
            self.base.train_iters,
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
            self.base.state.epoch,
            self.base.train_epochs,
        )

        for epoch in range(self.base.state.epoch, self.base.train_epochs):
            train_dataloader = self.base.train_dataloader
            if hasattr(train_dataloader, "set_epoch"):
                train_dataloader.set_epoch(epoch)

            self.base.on_epoch_begin()
            data_iterator = iter(train_dataloader)
            start_step = self.base.state.global_step - epoch * self.base.train_steps
            train_steps = min(self.base.train_steps, self.base.train_iters - epoch * self.base.train_steps)
            for _ in range(start_step, train_steps):
                try:
                    self.train_step(data_iterator)
                except StopIteration:
                    logger.info("epoch:%s Dataloader finished with drop_last %s", epoch, config.dataloader.drop_last)
                    break

            self.base.on_epoch_end()
            self.base.state.epoch = epoch + 1
            print_device_mem_info(f"VRAM usage after epoch {epoch + 1}")
            if self.base.state.global_step >= self.base.train_iters:
                break

        self.base.on_train_end()
        synchronize()
        self.base.destroy_distributed()


__all__ = ["DiTTrainer"]