From c95f8051345474225bb53738ec95f3436ee58abf Mon Sep 17 00:00:00 2001 From: niehen6174 <1639206518@qq.com> Date: Mon, 16 Nov 2026 10:21:57 +0800 Subject: [PATCH 1/2] feat(pdd): MiniMax H3 t2va PDD with video and audio heads Stacked on the Qwen-Image 2.1 PDD PR. H3 is the second model family, so the per-family registry comes back: - PDD_FAMILIES holds what differs per model: latent streams and their output layers, sigma grids, student/teacher time inputs, trajectory splitting, the rollout patch group, engine precision, FSDP param dtype and extra conditioning. Qwen-Image 2.1 keeps one "visual" stream; H3 adds "audio" on its own shifted grid (shift 12 / 3), BF16 engine weights with FP32 heads and the H3 FSDP plan. - The prepare hook samples one interval per block for all streams and runs one joint teacher call per midpoint stage; the loss sums the per-stream interval losses and logs pdd_audio_* and per-stream losses. Rollout trajectories are a dict of streams. - pdd_h3 rollout patch: live video/audio heads in place of the native output projections, the 8-step request run on the 32-interval grid with one DiT forward per block, and audio rows recorded and appended to the trajectory. Docs cover the H3 recipe and serving through sglang's native PDD path. CPU tests cover the H3 grids, stream splitting, both head stacks, the joint teacher call and H3 argument validation. --- docs/developer/pdd.md | 92 +++++++--- miles/backends/fsdp_utils/loss_hub/pdd.py | 85 +++++---- miles/backends/fsdp_utils/metrics.py | 4 + .../monkey_patches/__init__.py | 9 +- .../monkey_patches/patch_pdd_h3.py | 116 ++++++++++++ miles/distillation/integration.py | 154 +++++++++++++--- miles/distillation/pdd.py | 27 ++- miles/rollout/pdd_rollout.py | 13 +- .../test_pdd_sglang_loop.py | 6 +- tests/fast/distillation/test_pdd.py | 168 ++++++++++++++++-- 10 files changed, 570 insertions(+), 104 deletions(-) create mode 100644 miles/backends/sglang_diffusion_utils/monkey_patches/patch_pdd_h3.py diff --git a/docs/developer/pdd.md b/docs/developer/pdd.md index beee72e55..3f4880cd4 100644 --- a/docs/developer/pdd.md +++ b/docs/developer/pdd.md @@ -1,7 +1,8 @@ # PDD training in Miles This implementation adds Parallel Decoding Distillation (PDD) to -`train_diffusion.py` for Qwen-Image 2.1 text-to-image. SGLang rolls out the student, +`train_diffusion.py` for Qwen-Image 2.1 text-to-image and MiniMax H3 text-to-audio-video. +SGLang rolls out the student, the FSDP actor trains it against a frozen teacher, and the existing FSDP-to-engine weight sync closes the loop. It reuses the Ray actors, FSDP2 loader, loss hub, optimizer, dataset cursor and distributed @@ -9,8 +10,8 @@ checkpoints. ## Supported configuration -- 32 output heads, four intervals per block: eight student - forwards per sample. +- 32 output heads per latent stream, four intervals per block: eight student + forwards per sample. H3 trains a video and an audio head stack. - A LoRA student: adapters on the backbone, the new heads trained in full; FP32 master weights, BF16 compute; a frozen teacher loaded from the same base model. - The engine applies the adapter unmerged (`--lora-ipc-weight-sync` when colocated, @@ -22,25 +23,30 @@ checkpoints. - No EMA, RL log probabilities, reference-policy loss, dynamic batching, Cache-DiT or compiled/graph execution. -- Qwen-Image 2.1 t2i at 1024 × 1024 on the scheduler's shifted grid; FP32 engine - weights; FSDP all-gathers FP32 and computes under BF16 autocast. +What differs per model family lives in `PDD_FAMILIES` (`miles/distillation/integration.py`): + +| Family | Task | Streams | Grid | Engine weights | FSDP all-gather | +|---|---|---|---|---|---| +| `qwen_image21` | t2i, 1024 × 1024 | visual | the scheduler's shifted grid | FP32 | FP32, BF16 autocast | +| `h3` | t2va, short edge 768 | visual, audio | H3 shift 12 (video) / 3 (audio) | BF16, FP32 heads | the H3 FSDP plan (BF16, FP32 heads) | ## How it works 1. SGLang generates each prompt's trajectory with fixed student weights. The engine steps all 32 intervals: the first interval of each block runs the DiT and caches the 32 heads, the other three step on the cache, so the trajectory carries every - interval's start state (33 states) for eight DiT forwards. + interval's start state (33 states per stream) for eight DiT forwards. 2. After data-parallel splitting, each trajectory expands into its eight blocks. 3. Update j recomputes the heads from the rollout state at block j and samples one of its four intervals. The prepare hook asks the actor for the frozen teacher's - midpoint velocity from the rollout's state at that interval; the loss regresses the - selected head on it and steps once. Block j's states were produced j updates before the + midpoint velocity from the rollout's state at that interval, one joint teacher call + per midpoint stage for all streams; the loss regresses the selected head of every + stream on it and steps once. Block j's states were produced j updates before the weights it trains. 4. After the eight updates the driver synchronizes the student back to SGLang: the LoRA adapter, then the heads as plain weights. -The student's output layer is replicated into heads after LoRA is applied and before +The student's output layers are replicated into heads after LoRA is applied and before FSDP wrapping and optimizer creation, so the heads train in full beside the adapters and LoRA checkpoints keep them; all heads start from the base model's output layer. @@ -51,24 +57,32 @@ branches: | Hook | PDD default | |---|---| -| `--custom-train-model-transform-path` | `install_student`: `proj_out` as 32 heads, after LoRA | +| `--custom-train-model-transform-path` | `install_student`: each stream's output layer as 32 heads, after LoRA | | loss hub train input | `expand_train_pairs`: trajectory → eight block pairs | | loss hub prepare / formula | `loss_hub/pdd.py`; the teacher runs in the actor through `PreparedBatch.teacher_solver` | | `--custom-convert-samples-to-train-data-path` / `--custom-rm-path` | `miles/rollout/pdd_rollout.py` | -| `--rollout-patch-group` | `pdd_qwen_image21` | -| `--fsdp-param-dtype` | `fp32` | +| `--rollout-patch-group` | `pdd_qwen_image21` / `pdd_h3` | +| `--fsdp-param-dtype` | `fp32` (Qwen-Image 2.1) / the family plan (H3) | `validate_pdd_args` then rejects any configuration outside the validated scope. -### Rollout patch group +### Rollout patch groups + +Both groups keep the native Transformer forward, embeddings, norms and RoPE, and +replace only the output projections with the live heads that weight sync updates. -`pdd_qwen_image21` keeps the native Transformer forward, embeddings, norms and RoPE, -and replaces only the output projection with the live heads that weight sync updates. -It uses the trainer's 32-interval grid. Its timesteps are chosen so that the native +`pdd_qwen_image21` uses the trainer's 32-interval grid. Its timesteps are chosen so that the native DiT's BF16 time-embedding input equals the trainer's `bf16(sigma)`; when none reaches it, the trainer feeds the student the engine's embedded value. Native fused fast paths are disabled because they are verified only for BF16 engine weights. +`pdd_h3` turns an 8-step request into the 32-interval request (block boundaries are +every fourth point of H3's shifted grid, as for a native 8-step request). The native +rollout collector records video target rows; the patch also records the audio rows +after each step and appends them, zero-padded to the video width, to the trajectory, +which the family's `split_states` cuts back apart. Native fused PDD heads +(`pdd_fused_heads`) are rejected: training needs the live, unfused heads. + ## Train and resume ### Qwen-Image 2.1, validated on 2 × H200 with colocated training and rollout @@ -98,6 +112,41 @@ python train_diffusion.py \ --save "$OUTPUT/ckpt" --save-interval 100 ``` +### MiniMax H3 t2va on 8 × H200: four training GPUs and two rollout engines + +Each H3 engine holds a 48 GB text encoder, the 62 GB DiT and the VAEs; colocated, the +sleeping engines alone need about 1 TB of host memory, so the engines stay resident on +their own GPUs instead. The H3 FSDP plan keeps the heads, input projections and timestep +MLP in FP32, which needs the Miles FSDP param-dtype patch for the installed torch version. + +```bash +export MODEL=/path/to/MiniMax-H3-snapshot +python train_diffusion.py \ + --loss-type pdd --train-backend fsdp \ + --hf-checkpoint "$MODEL" --diffusion-model-family h3 --diffusion-task t2va \ + --prompt-data "$PROMPTS" --input-key input \ + --rollout-batch-size 8 --n-samples-per-prompt 1 \ + --rollout-microgroup-size 1 --num-rollout 400 --micro-batch-size 1 --gradient-checkpointing \ + --fsdp-master-dtype fp32 --fsdp-reduce-dtype fp32 --diffusion-forward-dtype bf16 \ + --diffusion-h3-aspect-ratio 1:1 --diffusion-h3-duration-seconds 4 \ + --diffusion-flow-shift 12 --diffusion-audio-flow-shift 3 \ + --diffusion-num-steps 8 --diffusion-eval-num-steps 8 \ + --diffusion-sde-type ode --diffusion-noise-level 0 --diffusion-guidance-scale 1 \ + --use-lora --lora-rank 64 --lora-alpha 128 --sglang-lora-merge-mode dynamic \ + --lr 5e-6 --weight-decay 0 --adam-beta2 0.999 --seed 42 \ + --sglang-dit-precision bf16 --sglang-tp-size 1 --sglang-model-variant fl2va \ + --use-miles-router --update-weight-buffer-size 2147483648 \ + --actor-num-gpus-per-node 4 --num-gpus-per-node 6 \ + --rollout-num-gpus 2 --rollout-num-gpus-per-engine 1 \ + --save "$OUTPUT/ckpt" --save-interval 50 +``` + +To serve an H3 student with SGLang's native PDD path, export the LoRA adapter and the +32 heads from the checkpoint, fuse the heads with +`python -m sglang.multimodal_gen.tools.fuse_minimax_h3_pdd_heads `, and run 8 steps +with `--lora-path --lora-merge-mode dynamic` and +`SGLANG_DIFFUSION_MINIMAX_H3_PDD_HEADS=/pdd_fused_heads.safetensors`. + Optionally add `--eval-prompt-data --eval-interval 50` to render fixed prompts with the current student in SGLang. The rollout's reward field is a zero placeholder, **not** a quality metric. @@ -108,7 +157,8 @@ PDD uses the standard FSDP checkpoint (model, optimizer, scheduler, RNG, dataset cursor), written at rollout boundaries; interval selection is a hash of seed, rollout, lane and block, so it does not depend on RNG state. -`train/pdd_next_latent_mae` and `train/pdd_update_relative_error` compare the +`train/pdd_next_latent_mae` and `train/pdd_update_relative_error` (H3 also +`train/pdd_audio_*` and the per-stream `train/pdd_{visual,audio}_loss`) compare the trainer's next block state with the one SGLang recorded. Block 0 measures pure engine/trainer parity; later blocks also include rollout staleness. @@ -122,13 +172,15 @@ python -m pytest tests/fast-gpu/backends/sglang_diffusion_utils/test_pdd_sglang_ The CPU tests cover the interval math on signed nonuniform grids, the detached midpoint teacher target, the engine's cached-head interval steps, timestep matching, trajectory validation, the LoRA student's trainable and checkpointed parameters, -unsupported configurations, and eight block updates from rollout states against an -independent optimizer loop (the test plays the actor's teacher solve). The GPU smoke +unsupported configurations, eight block updates from rollout states against an +independent optimizer loop (the test plays the actor's teacher solve), and H3's grids, +stream splitting, two head stacks and joint two-stream teacher call. The GPU smoke runs a tiny Qwen-Image 2.1 through SGLang's native stages, the response parser, one-rank FSDP with a LoRA student, the PDD loss and the Miles weight iterator into SGLang's weight receiver: one rollout, eight updates and a sync, then checks every interval of the next rollout against the trainer within 0.5%. It does not exercise the -HTTP/Ray driver, pretrained quality or multi-GPU placement, and skips without CUDA. +HTTP/Ray driver, H3's native stages, pretrained quality or multi-GPU placement, and +skips without CUDA. These are correctness checks, not quality claims. Automatic image/video metrics, historical datasets/reports and experiment orchestration are outside this change. diff --git a/miles/backends/fsdp_utils/loss_hub/pdd.py b/miles/backends/fsdp_utils/loss_hub/pdd.py index cbd8688be..f5e30c9b6 100644 --- a/miles/backends/fsdp_utils/loss_hub/pdd.py +++ b/miles/backends/fsdp_utils/loss_hub/pdd.py @@ -1,33 +1,40 @@ """PDD prepare/loss hooks. The FSDP actor owns every DiT forward: the student's, and the teacher's midpoint solve from the rollout's interval state, requested by prepare. + +Every latent stream of the family (H3: video and audio) moves on its own grid; one +sampled interval and one joint teacher call cover all streams. """ import torch -from miles.distillation.integration import model_time, pdd_grid +from miles.distillation.integration import pdd_family from miles.distillation.pdd import block_update, interval_loss, teacher_mean_velocity from miles.utils.hash_utils import stable_hash from .types import PreparedBatch -STREAM = "visual" - def prepare_pdd_batch(ctx, batch, *, microbatch_id, optim_step_idx, pad_to_len=None): if len(batch) != 1 or pad_to_len is not None: raise ValueError("PDD supports one unpadded sample per microbatch") pair = batch[0] args = ctx.args + family = pdd_family(args) start, lane = pair["pdd_start"], pair["sample_index"] if start not in range(0, args.pdd_num_intervals, args.pdd_block_size): raise ValueError("Invalid PDD rollout block index") - grid = pdd_grid(args).to(ctx.device) + grids = {stream: grid.to(ctx.device) for stream, grid in family.grids(args).items()} generator = torch.Generator().manual_seed(stable_hash("pdd-interval", args.seed, ctx.rollout_id, lane, start)) selected = int(torch.randint(start, start + args.pdd_block_size, (), generator=generator)) # The block and the teacher both start from fixed-weight SGLang rollout states (indexed by interval). trajectory = pair["pdd_trajectory"] - x_start, x_selected = (trajectory[i].to(ctx.device).unsqueeze(0).float() for i in (start, selected)) - if not torch.isfinite(x_start).all(): + if set(trajectory) != set(family.heads): + raise ValueError(f"PDD rollout streams {sorted(trajectory)} differ from {sorted(family.heads)}") + x_start, x_selected = ( + {stream: trajectory[stream][i].to(ctx.device).unsqueeze(0).float() for stream in family.heads} + for i in (start, selected) + ) + if not all(torch.isfinite(state).all() for state in x_start.values()): raise ValueError("Invalid PDD rollout latent values") condition = ctx.train_pipeline_config.prepare_cond_kwargs(pair["denoising_env"].pos_cond_kwargs, ctx.device) # FP32 conditioning boundary; autocast controls matmuls. @@ -39,18 +46,27 @@ def prepare_pdd_batch(ctx, batch, *, microbatch_id, optim_step_idx, pad_to_len=N ) for k, v in condition.items() } + condition.update(family.cond_extras) def solve(forward): def teacher(x, sigma): - return forward({STREAM: x}, {STREAM: sigma.reshape(1)})[STREAM].float() + timesteps = { + stream: family.teacher_time(args, stream, value.reshape(1)) for stream, value in sigma.items() + } + pred = forward(x, timesteps) + return {stream: pred[stream].float() for stream in x} - target = teacher_mean_velocity(teacher, x_selected, grid[selected], grid.diff()[selected], solver="midpoint") - return {STREAM: target} + sigma = {stream: grid[selected] for stream, grid in grids.items()} + delta = {stream: grid.diff()[selected] for stream, grid in grids.items()} + return teacher_mean_velocity(teacher, x_selected, sigma, delta, solver="midpoint") return PreparedBatch( - latents={STREAM: x_start}, - timesteps={STREAM: grid[start].reshape(1)}, - timesteps_for_model={STREAM: model_time(grid[start].reshape(1)).to(ctx.device)}, + latents=x_start, + timesteps={stream: grid[start].reshape(1) for stream, grid in grids.items()}, + timesteps_for_model={ + stream: family.model_time(args, stream, grid[start].reshape(1)).to(ctx.device) + for stream, grid in grids.items() + }, model=ctx.models["transformer"], component_name="transformer", guidance_scale=1.0, @@ -61,7 +77,7 @@ def teacher(x, sigma): neg_cond=None, joint_cond=None, advantage=torch.ones(1, device=ctx.device), - extras={"start": start, "selected": selected, "lane": lane, "grid": grid}, + extras={"start": start, "selected": selected, "lane": lane, "grids": grids}, teacher_guidance_scale=1.0, teacher_solver=solve, ) @@ -87,25 +103,32 @@ def pdd_loss_formula( if teacher_pred is None: raise ValueError("PDD needs the teacher target its prepare hook requested") n = ctx.args.pdd_num_intervals - start, selected, grid = (prepared.extras[k] for k in ("start", "selected", "grid")) + start, selected, grids = (prepared.extras[k] for k in ("start", "selected", "grids")) end = start + ctx.args.pdd_block_size - x, raw = prepared.latents[STREAM], new_pred[STREAM] - if raw.shape != (*x.shape[:-1], n * x.shape[-1]): - raise ValueError("PDD student output shape does not match the parallel heads") - # [B, S, N*C] -> [N, B, S, C] - predictions = raw.reshape(*x.shape[:-1], n, x.shape[-1]).permute(2, 0, 1, 3) - per_sample_loss = interval_loss(predictions, selected, teacher_pred[STREAM]) - if not torch.isfinite(per_sample_loss).all(): - raise FloatingPointError("nonfinite PDD loss") + per_sample_loss = 0 + for stream, x in prepared.latents.items(): + raw = new_pred[stream] + if raw.shape != (*x.shape[:-1], n * x.shape[-1]): + raise ValueError(f"PDD student {stream} output shape does not match the parallel heads") + # [B, S, N*C] -> [N, B, S, C] + predictions = raw.reshape(*x.shape[:-1], n, x.shape[-1]).permute(2, 0, 1, 3) + stream_loss = interval_loss(predictions, selected, teacher_pred[stream]) + if not torch.isfinite(stream_loss).all(): + raise FloatingPointError(f"nonfinite PDD {stream} loss") + per_sample_loss = per_sample_loss + stream_loss + with torch.no_grad(): + following = block_update(x, predictions, grids[stream], start, end) + if not torch.isfinite(following).all(): + raise FloatingPointError(f"nonfinite PDD {stream} trajectory") + # Trainer vs. engine next state; later blocks also include rollout staleness. + expected = batch[0]["pdd_trajectory"][stream][end].to(ctx.device).unsqueeze(0).float() + error = (following - expected).abs() + prefix = "pdd" if stream == "visual" else f"pdd_{stream}" + metrics.emit_mean(f"{prefix}_next_latent_mae", total=error.sum(), count=error.numel()) + relative = error.mean() / (expected - x).abs().mean().clamp_min(1e-6) + metrics.emit_mean(f"{prefix}_update_relative_error", total=relative, count=1) + if len(prepared.latents) > 1: + metrics.emit_mean(f"pdd_{stream}_loss", total=stream_loss.sum(), count=len(batch)) with torch.no_grad(): - following = block_update(x, predictions, grid, start, end) - if not torch.isfinite(following).all(): - raise FloatingPointError("nonfinite PDD trajectory") - # Trainer vs. engine next state; later blocks also include rollout staleness. - expected = batch[0]["pdd_trajectory"][end].to(ctx.device).unsqueeze(0).float() - error = (following - expected).abs() - metrics.emit_mean("pdd_next_latent_mae", total=error.sum(), count=error.numel()) - relative = error.mean() / (expected - x).abs().mean().clamp_min(1e-6) - metrics.emit_mean("pdd_update_relative_error", total=relative, count=1) metrics.emit_mean("loss", total=per_sample_loss.sum(), count=len(batch)) return per_sample_loss.sum() diff --git a/miles/backends/fsdp_utils/metrics.py b/miles/backends/fsdp_utils/metrics.py index 277e28d87..a40cc144c 100644 --- a/miles/backends/fsdp_utils/metrics.py +++ b/miles/backends/fsdp_utils/metrics.py @@ -48,6 +48,10 @@ "device_memory_used_gb": MetricReduce.MAX, "pdd_next_latent_mae": MetricReduce.MEAN, "pdd_update_relative_error": MetricReduce.MEAN, + "pdd_audio_next_latent_mae": MetricReduce.MEAN, + "pdd_audio_update_relative_error": MetricReduce.MEAN, + "pdd_visual_loss": MetricReduce.MEAN, + "pdd_audio_loss": MetricReduce.MEAN, } # Also logged per rollout denoising step, under step_metric_key; a step no pair trained on is not logged. diff --git a/miles/backends/sglang_diffusion_utils/monkey_patches/__init__.py b/miles/backends/sglang_diffusion_utils/monkey_patches/__init__.py index 2ac94191e..e757cd5a4 100644 --- a/miles/backends/sglang_diffusion_utils/monkey_patches/__init__.py +++ b/miles/backends/sglang_diffusion_utils/monkey_patches/__init__.py @@ -9,7 +9,7 @@ - ``qwen_image21``: Qwen-Image 2.1 recomputes the text prefix every step instead of caching its K/V, like the trainer. - ``ltx``: LTX rollout cond kwargs + AV cross-off (video-only train parity). -- ``pdd_qwen_image21``: PDD student heads and per-interval trajectories (``docs/developer/pdd.md``). +- ``pdd_qwen_image21`` / ``pdd_h3``: PDD student heads and per-interval trajectories (``docs/developer/pdd.md``). Patch modules are imported inside ``apply_*`` only, so CPU-only Ray actors can import this package without pulling sglang triton kernels. Adding a @@ -65,6 +65,13 @@ def apply_pdd_qwen_image21_rollout_patches() -> None: patch_pdd_qwen_image21.apply() +@register_rollout_patch_group("pdd_h3") +def apply_pdd_h3_rollout_patches() -> None: + from . import patch_pdd_h3 + + patch_pdd_h3.apply() + + @register_rollout_patch_group("ltx") def apply_ltx2_rollout_patches() -> None: from miles.backends.sglang_diffusion_utils.monkey_patches import ( diff --git a/miles/backends/sglang_diffusion_utils/monkey_patches/patch_pdd_h3.py b/miles/backends/sglang_diffusion_utils/monkey_patches/patch_pdd_h3.py new file mode 100644 index 000000000..6e4251b5a --- /dev/null +++ b/miles/backends/sglang_diffusion_utils/monkey_patches/patch_pdd_h3.py @@ -0,0 +1,116 @@ +"""PDD rollout for MiniMax H3 t2va. Keep the native DiT, denoise loop and rollout collector. + +The native video and audio output projections become 32 heads each. The loop steps all +32 intervals of the shifted grids (one per H3 grid point of a 32-step request): the first +interval of each block runs the DiT and caches every head, the block's other three step on +the cache without a forward. The rollout trajectory returns each interval's start state of +both streams: video target rows, then audio rows zero-padded to the video width, which the +trainer's ``split_states`` cuts back apart. +""" + +import torch +from torch import nn + +from miles.distillation.integration import BLOCK_SIZE as BLOCK +from miles.distillation.integration import NUM_INTERVALS as INTERVALS +from miles.distillation.pdd import ParallelLinear + + +class PDDHeads(nn.Module): + """A native output projection as N heads, returned like ``ColumnParallelLinear``: ([rows, N*C], None).""" + + def __init__(self, source): + super().__init__() + self.parallel = ParallelLinear(source, INTERVALS) + + def forward(self, hidden): + return self.parallel(hidden).permute(1, 0, 2).flatten(1), None + + +def apply(): + from sglang.multimodal_gen.runtime.distributed import get_sp_world_size, get_tp_world_size + from sglang.multimodal_gen.runtime.models.dits.minimax_h3 import MiniMaxH3DiTModel + from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3 import ( + denoise_loop, + minimax_h3_rollout, + ) + from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.stages import ( + denoising, + timestep_preparation, + ) + + stage_cls = denoising.MiniMaxH3DenoisingStage + if getattr(stage_cls, "_miles_pdd", False): + return + original_load = MiniMaxH3DiTModel.post_load_weights + original_time = timestep_preparation.MiniMaxH3TimestepPreparationStage.forward + original_forward = stage_cls._forward_dit + original_loop = denoise_loop.minimax_h3_denoise_loop + original_build = minimax_h3_rollout.MiniMaxH3RolloutCollector.build_trajectory_data + + def post_load(self): + original_load(self) + if get_tp_world_size() != 1 or get_sp_world_size() != 1: + raise ValueError("H3 PDD stacks the heads per GPU; serve with TP=SP=1") + if self.final_layer._pdd_heads is not None: + raise ValueError("H3 PDD trains live heads; do not load fused PDD heads") + for name in ("video_out", "audio_out"): + if not isinstance(getattr(self.final_layer, name), PDDHeads): + setattr(self.final_layer, name, PDDHeads(getattr(self.final_layer, name))) + + def timesteps(self, batch, server_args): + # A request for 8 steps runs the 32-interval grid; block boundaries are its every 4th point. + if batch.num_inference_steps != INTERVALS // BLOCK: + raise ValueError(f"H3 PDD requires {INTERVALS // BLOCK} inference steps") + batch.num_inference_steps = INTERVALS + return original_time(self, batch, server_args) + + def forward_dit(self, model, call_kwargs, step_index, **kwargs): + if step_index % BLOCK == 0: + video, audio = original_forward(self, model, call_kwargs, step_index, **kwargs) + model._miles_pdd_block = (video.unflatten(-1, (INTERVALS, -1)), audio.unflatten(-1, (INTERVALS, -1))) + video, audio = model._miles_pdd_block + return video[:, step_index].contiguous(), audio[:, step_index].contiguous() + + def loop(*, positive, initial_audio_rows, on_step=None, rollout_ctx=None, **kwargs): + if rollout_ctx is None: + return original_loop(positive=positive, initial_audio_rows=initial_audio_rows, on_step=on_step, **kwargs) + audio_target = positive.audio_target_slice + collector = rollout_ctx.collector + collector.audio_steps = [initial_audio_rows[audio_target].detach().float().cpu().clone()] + + def record(step, video_rows, audio_rows): + # Called after both streams moved, so this is the audio state at interval step + 1. + collector.audio_steps.append(audio_rows[audio_target].detach().float().cpu().clone()) + if on_step is not None: + on_step(step, video_rows, audio_rows) + + return original_loop( + positive=positive, + initial_audio_rows=initial_audio_rows, + on_step=record, + rollout_ctx=rollout_ctx, + **kwargs, + ) + + def build(self): + data = original_build(self) + audio = getattr(self, "audio_steps", None) + if audio is None: + return data + trajectory = data.dit_trajectory + video = trajectory.latents + if trajectory.latent_step_indices.tolist() != list(range(len(audio))): + raise ValueError("H3 PDD needs the full trajectory of both streams") + audio = torch.stack(audio).to(video.dtype).unsqueeze(0) + padded = audio.new_zeros(*audio.shape[:-1], video.shape[-1]) + padded[..., : audio.shape[-1]] = audio + trajectory.latents = torch.cat((video, padded), dim=2) + return data + + MiniMaxH3DiTModel.post_load_weights = post_load + timestep_preparation.MiniMaxH3TimestepPreparationStage.forward = timesteps + stage_cls._forward_dit = forward_dit + denoise_loop.minimax_h3_denoise_loop = loop + minimax_h3_rollout.MiniMaxH3RolloutCollector.build_trajectory_data = build + stage_cls._miles_pdd = True diff --git a/miles/distillation/integration.py b/miles/distillation/integration.py index 7a32f05f7..7ec6b62cc 100644 --- a/miles/distillation/integration.py +++ b/miles/distillation/integration.py @@ -2,10 +2,15 @@ SGLang rolls out each 8-block trajectory with fixed student weights; the actor then takes one optimizer update per block, in block order. ``set_pdd_defaults`` wires the -generic Miles hooks; nothing in the trainer branches on ``--loss-type pdd``. +generic Miles hooks; nothing in the trainer branches on ``--loss-type pdd``. What +differs per model family (latent streams, sigma grids, time inputs, rollout patch) +lives in ``PDD_FAMILIES``. """ import functools +from collections.abc import Callable +from dataclasses import dataclass, field +from typing import Any import torch @@ -59,6 +64,14 @@ def embedded_sigmas(timesteps): return (timesteps.bfloat16() / 1000).float() +def h3_grid(num_intervals, shift): + """MiniMax H3's shifted rectified-flow grid, computed like sgl-d's ``minimax_h3_time_shift_sigmas``.""" + base = torch.linspace(1.0, 0.0, num_intervals + 1, dtype=torch.float32) + grid = float(shift) * base / (1 + (float(shift) - 1) * base) + validate_grid(grid) + return grid + + class TokenParallelProjection(torch.nn.Module): """An output layer as N heads, emitted as [B, S, N*C] so token selection and masks stay row-wise.""" @@ -70,29 +83,111 @@ def forward(self, hidden): return self.parallel(hidden).permute(1, 2, 0, 3).flatten(2) -# Validated scope: Qwen-Image 2.1 t2i at 1024 x 1024, 32 intervals in blocks of 4 (8 student forwards). +# Validated scope: 32 intervals in blocks of 4 (8 student forwards); Qwen-Image 2.1 t2i at 1024 x 1024. NUM_INTERVALS, BLOCK_SIZE = 32, 4 RESOLUTION = 1024 IMAGE_TOKENS = (RESOLUTION // 16) ** 2 -PATCH_GROUP = "pdd_qwen_image21" +H3_AUDIO_CHANNELS = 32 + +@dataclass(frozen=True) +class PDDFamily: + """What PDD needs from one model family, looked up by ``--diffusion-model-family``. -def pdd_grid(args): - """The (N+1)-point sigma grid the rollout and the trainer share.""" - return make_grid(args.hf_checkpoint, args.pdd_num_intervals, IMAGE_TOKENS) + ``heads`` maps each latent stream to the Diffusers transformer's output layer that becomes N heads; + ``grids(args)`` gives each stream's (N+1)-point sigma grid; ``model_time`` / ``teacher_time`` turn a grid + sigma into the student's and the teacher's ``timesteps_for_model``; ``split_states`` cuts the rollout's + per-interval states into streams; ``validate`` checks the family's rollout settings. + """ + task: str + heads: dict[str, str] + patch_group: str + engine_precision: str + # None keeps the family's FSDP plan (e.g. FP32 heads over a BF16 all-gather). + fsdp_param_dtype: str | None + grids: Callable[[Any], dict[str, torch.Tensor]] + model_time: Callable[[Any, str, torch.Tensor], torch.Tensor] + teacher_time: Callable[[Any, str, torch.Tensor], torch.Tensor] + split_states: Callable[[torch.Tensor, Any], dict[str, torch.Tensor]] + validate: Callable[[Any], None] + cond_extras: dict[str, Any] = field(default_factory=dict) + + +def _qwen_validate(args): + if (args.diffusion_height, args.diffusion_width) != (RESOLUTION, RESOLUTION): + raise ValueError(f"PDD requires {RESOLUTION} x {RESOLUTION} for Qwen-Image 2.1") + + +def _h3_split_states(states, env): + """The H3 rollout packs video target rows, then audio rows zero-padded to the video width.""" + layout = env.pos_cond_kwargs.h3_packed_layout + videos, audios = int(layout["update_mask"].sum()), int(layout["audio_pos"].numel()) + if states.shape[1] != videos + audios: + raise ValueError(f"H3 PDD trajectory has {states.shape[1]} rows, layout has {videos} video + {audios} audio") + if states[:, videos:, H3_AUDIO_CHANNELS:].any(): + raise ValueError("H3 PDD audio rows carry data beyond the audio width") + return {"visual": states[:, :videos], "audio": states[:, videos:, :H3_AUDIO_CHANNELS]} + + +def _h3_validate(args): + if args.diffusion_flow_shift is None or args.diffusion_audio_flow_shift is None: + raise ValueError("H3 PDD requires --diffusion-flow-shift and --diffusion-audio-flow-shift for its grids") + if args.sglang_tp_size not in (None, 1) or args.sglang_sp_degree not in (None, 1): + raise ValueError("H3 PDD engines stack the heads per GPU; use --sglang-tp-size 1 --sglang-sp-degree 1") + + +PDD_FAMILIES = { + "qwen_image21": PDDFamily( + task="t2i", + heads={"visual": "proj_out"}, + patch_group="pdd_qwen_image21", + engine_precision="fp32", + # Gathered student weights stay FP32 (head biases, norms); autocast handles matmuls. + fsdp_param_dtype="fp32", + grids=lambda args: {"visual": make_grid(args.hf_checkpoint, args.pdd_num_intervals, IMAGE_TOKENS)}, + # The student sees the time value SGLang's native DiT embedded; the grid dynamics stay unchanged. + model_time=lambda args, stream, sigma: embedded_sigmas(engine_timesteps(sigma)), + teacher_time=lambda args, stream, sigma: sigma, + split_states=lambda states, env: {"visual": states}, + validate=_qwen_validate, + ), + "h3": PDDFamily( + task="t2va", + heads={"visual": "proj_out", "audio": "audio_proj_out"}, + patch_group="pdd_h3", + # The native engine keeps BF16 blocks and FP32 output heads, as the trainer's FSDP plan does. + engine_precision="bf16", + fsdp_param_dtype=None, + grids=lambda args: { + "visual": h3_grid(args.pdd_num_intervals, args.diffusion_flow_shift), + "audio": h3_grid(args.pdd_num_intervals, args.diffusion_audio_flow_shift), + }, + model_time=lambda args, stream, sigma: sigma * 1000.0, + teacher_time=lambda args, stream, sigma: sigma * 1000.0, + split_states=_h3_split_states, + validate=_h3_validate, + # Audio rows are PDD targets: the H3 forward returns their prediction only for a soundtrack target. + cond_extras={"h3_target_has_soundtrack": True}, + ), +} -def model_time(sigma): - """The student's time input: the value SGLang's native DiT embedded. The grid dynamics stay unchanged.""" - return embedded_sigmas(engine_timesteps(sigma)) + +def pdd_family(args): + try: + return PDD_FAMILIES[args.diffusion_model_family] + except KeyError: + raise ValueError(f"PDD supports --diffusion-model-family {sorted(PDD_FAMILIES)}") from None def install_student(model, args): - """``--custom-train-model-transform-path`` hook: the output layer becomes N heads, trained in full beside - the backbone's LoRA adapters.""" - if not isinstance(model.proj_out, torch.nn.Linear): - raise ValueError("PDD needs an unmodified proj_out output layer") - model.proj_out = TokenParallelProjection(model.proj_out, args.pdd_num_intervals) + """``--custom-train-model-transform-path`` hook: each stream's output layer becomes N heads, trained in + full beside the backbone's LoRA adapters.""" + for attr in pdd_family(args).heads.values(): + layer = getattr(model, attr) + if not isinstance(layer, torch.nn.Linear): + raise ValueError(f"PDD needs an unmodified {attr} output layer") + setattr(model, attr, TokenParallelProjection(layer, args.pdd_num_intervals)) def expand_trajectories(pairs, *, intervals, block_size): @@ -123,11 +218,12 @@ def set_pdd_defaults(args): setattr(args, key, value) if args.rollout_function_path == "miles.rollout.sglang_rollout.generate_rollout": args.rollout_function_path = _DIFFUSION_ROLLOUT - if args.rollout_patch_group is None: - args.rollout_patch_group = PATCH_GROUP - # Gathered student weights stay FP32 (head biases, norms); autocast handles matmuls. - if args.fsdp_param_dtype is None: - args.fsdp_param_dtype = "fp32" + family = PDD_FAMILIES.get(args.diffusion_model_family) + if family is not None: + if args.rollout_patch_group is None: + args.rollout_patch_group = family.patch_group + if args.fsdp_param_dtype is None: + args.fsdp_param_dtype = family.fsdp_param_dtype if args.teacher_load is None: args.teacher_load = args.hf_checkpoint args.rollout_return_full_trajectory = True @@ -140,10 +236,10 @@ def set_pdd_defaults(args): def validate_pdd_args(args): """Narrow, validated integration; unsupported modes fail before loading GPUs.""" - if args.diffusion_model_family != "qwen_image21" or args.diffusion_task != "t2i": - raise ValueError("PDD supports Qwen-Image 2.1 t2i only") - if (args.diffusion_height, args.diffusion_width) != (RESOLUTION, RESOLUTION): - raise ValueError(f"PDD requires {RESOLUTION} x {RESOLUTION}") + family = pdd_family(args) + if args.diffusion_task != family.task: + raise ValueError(f"PDD supports {args.diffusion_model_family} {family.task} only") + family.validate(args) if args.train_only or args.train_backend != "fsdp": raise ValueError("PDD trains on FSDP from SGLang rollouts; drop --train-only") if args.update_weight_target_modules != ["transformer"]: @@ -186,14 +282,14 @@ def validate_pdd_args(args): raise ValueError("PDD requires --diffusion-sde-type ode --diffusion-noise-level 0") if args.rollout_num_gpus_per_engine != 1 or args.rollout_microgroup_size != 1: raise ValueError("PDD requires one GPU per engine and rollout microgroup size 1") - if args.sglang_dit_precision != "fp32": - raise ValueError("PDD requires --sglang-dit-precision fp32") - if args.fsdp_param_dtype != "fp32": - raise ValueError("PDD requires --fsdp-param-dtype fp32") + if args.sglang_dit_precision != family.engine_precision: + raise ValueError(f"PDD requires --sglang-dit-precision {family.engine_precision}") + if args.fsdp_param_dtype != family.fsdp_param_dtype: + raise ValueError(f"PDD requires --fsdp-param-dtype {family.fsdp_param_dtype}") if args.diffusion_step_strategy_path or args.custom_generate_function_path or args.group_rm: raise ValueError("PDD requires the standard full-trajectory rollout without custom generation/group RM") - if args.rollout_patch_groups != [PATCH_GROUP]: - raise ValueError(f"PDD requires only the {PATCH_GROUP} rollout patch group") + if args.rollout_patch_groups != [family.patch_group]: + raise ValueError(f"PDD requires only the {family.patch_group} rollout patch group") for key, value in {**_HOOK_DEFAULTS, "rollout_function_path": _DIFFUSION_ROLLOUT}.items(): if getattr(args, key) != value: raise ValueError(f"PDD requires {key}={value}") diff --git a/miles/distillation/pdd.py b/miles/distillation/pdd.py index ba0eb02b6..aa754251e 100644 --- a/miles/distillation/pdd.py +++ b/miles/distillation/pdd.py @@ -42,23 +42,38 @@ def forward(self, hidden: torch.Tensor) -> torch.Tensor: return result +def _each(fn, *trees): + """Apply ``fn`` leafwise over tensors or same-keyed dicts of tensors (one entry per latent stream).""" + if isinstance(trees[0], dict): + return {key: fn(*(tree[key] for tree in trees)) for key in trees[0]} + return fn(*trees) + + @torch.no_grad() -def teacher_mean_velocity(teacher: Callable, x: torch.Tensor, time, delta, solver: str = "midpoint") -> torch.Tensor: - """Teacher closure includes conditioning/CFG; never build a teacher gradient graph.""" +def teacher_mean_velocity(teacher: Callable, x, time, delta, solver: str = "midpoint"): + """Teacher closure includes conditioning/CFG; never build a teacher gradient graph. + + ``x``, ``time`` and ``delta`` are tensors, or dicts keyed by latent stream for a joint + model whose streams move on their own grids in one teacher call. + """ if solver not in {"euler", "midpoint"}: raise ValueError("solver must be euler or midpoint") def call(state, t): velocity = teacher(state, t) - if velocity.shape != state.shape: + pairs = [(velocity[k], state[k]) for k in state] if isinstance(state, dict) else [(velocity, state)] + if any(v.shape != s.shape for v, s in pairs): raise ValueError("teacher output must match the latent shape exactly") return velocity - x = x.detach() + x = _each(torch.Tensor.detach, x) velocity = call(x, time) if solver == "midpoint": - velocity = call(x + 0.5 * delta * velocity, time + 0.5 * delta) - return velocity.detach() + velocity = call( + _each(lambda s, d, v: s + 0.5 * d * v, x, delta, velocity), + _each(lambda t, d: t + 0.5 * d, time, delta), + ) + return _each(torch.Tensor.detach, velocity) def block_update(x: torch.Tensor, predictions: torch.Tensor, grid: torch.Tensor, start: int, end: int) -> torch.Tensor: diff --git a/miles/rollout/pdd_rollout.py b/miles/rollout/pdd_rollout.py index 9bdd4e018..bcfb94963 100644 --- a/miles/rollout/pdd_rollout.py +++ b/miles/rollout/pdd_rollout.py @@ -1,6 +1,7 @@ """PDD rollout hooks: validate SGLang trajectories for the block-ordered updates. -SGLang returns the start state of all 32 intervals plus the endpoint. The actor +SGLang returns the start state of all 32 intervals plus the endpoint, per latent +stream (the family's ``split_states`` cuts a packed H3 trajectory). The actor expands each trajectory into its eight blocks after DP splitting; block j trains from the rollout state at its first interval, and the teacher target starts from the rollout state at the sampled interval. Uses the shared rollout engine, response @@ -9,7 +10,7 @@ import torch -from miles.distillation.integration import pdd_grid +from miles.distillation.integration import pdd_family async def no_reward(args, samples, **kwargs): @@ -19,7 +20,9 @@ async def no_reward(args, samples, **kwargs): def convert_samples_to_train_data(args, samples): - grid = pdd_grid(args) + family = pdd_family(args) + # The rollout records its trajectory on the video grid; H3's audio grid only differs in shift. + grid = family.grids(args)["visual"] states_count = args.pdd_num_intervals + 1 pairs = [] for sample in samples: @@ -39,7 +42,9 @@ def convert_samples_to_train_data(args, samples): raise ValueError(f"PDD expects per-sample packed latent tokens [{states_count}, S, C]") if not torch.isfinite(states).all(): raise ValueError("PDD rollout contains nonfinite states") - pairs.append(dict(sample_index=sample.index, pdd_trajectory=states, denoising_env=env)) + pairs.append( + dict(sample_index=sample.index, pdd_trajectory=family.split_states(states, env), denoising_env=env) + ) if not pairs: raise ValueError("PDD rollout produced no training samples") return {"train_data": pairs} diff --git a/tests/fast-gpu/backends/sglang_diffusion_utils/test_pdd_sglang_loop.py b/tests/fast-gpu/backends/sglang_diffusion_utils/test_pdd_sglang_loop.py index 6fc953c9a..e894b7c52 100644 --- a/tests/fast-gpu/backends/sglang_diffusion_utils/test_pdd_sglang_loop.py +++ b/tests/fast-gpu/backends/sglang_diffusion_utils/test_pdd_sglang_loop.py @@ -263,15 +263,15 @@ def forward(latents, timesteps): # The trained heads now drive the engine; every interval state must match the trainer's heads. second = rollout() - assert not torch.equal(first["pdd_trajectory"], second["pdd_trajectory"]) + assert not torch.equal(first["pdd_trajectory"]["visual"], second["pdd_trajectory"]["visual"]) with torch.no_grad(): for block in expand_train_pairs(ctx, [second]): prepared = prepare_pdd_batch(ctx, [block], microbatch_id=0, optim_step_idx=0) x, start = prepared.latents["visual"], block["pdd_start"] heads = predict(prepared)["visual"].reshape(*x.shape[:-1], 32, x.shape[-1]).permute(2, 0, 1, 3) for end in range(start + 1, start + 5): - following = block_update(x, heads, prepared.extras["grid"], start, end) - expected = second["pdd_trajectory"][end].cuda().unsqueeze(0) + following = block_update(x, heads, prepared.extras["grids"]["visual"], start, end) + expected = second["pdd_trajectory"]["visual"][end].cuda().unsqueeze(0) # Mismatched BF16 timestep rounding alone gave 1.5-3% on some blocks. relative = (following - expected).abs().mean() / (expected - x).abs().mean() assert relative < 5e-3, (start, end, float(relative)) diff --git a/tests/fast/distillation/test_pdd.py b/tests/fast/distillation/test_pdd.py index 24b90f30d..5ce4962d7 100644 --- a/tests/fast/distillation/test_pdd.py +++ b/tests/fast/distillation/test_pdd.py @@ -1,5 +1,6 @@ -"""PDD on CPU: the interval math, the engine's cached-head steps, and eight block updates from rollout -states against an independent optimizer loop. The tests play the actor where it would run the teacher.""" +"""PDD on CPU: the interval math, the engine's cached-head steps, eight block updates from rollout +states against an independent optimizer loop, and H3's two latent streams. The tests play the actor +where it would run the teacher.""" from tests.ci.ci_register import register_cpu_ci @@ -104,9 +105,9 @@ def test_converter_accepts_only_the_full_trajectory_on_the_training_grid(): denoising_env=SimpleNamespace(pos_cond_kwargs={}), dit_trajectory=SimpleNamespace(sigmas=GRID, latents=torch.randn(33, 4, 2), latent_step_indices=None), ) - args = SimpleNamespace(hf_checkpoint="unused", pdd_num_intervals=32) + args = SimpleNamespace(hf_checkpoint="unused", pdd_num_intervals=32, diffusion_model_family="qwen_image21") pair = pdd_rollout.convert_samples_to_train_data(args, [sample])["train_data"][0] - torch.testing.assert_close(pair["pdd_trajectory"], sample.dit_trajectory.latents) + torch.testing.assert_close(pair["pdd_trajectory"]["visual"], sample.dit_trajectory.latents) for field, value in [ ("sigmas", GRID + 0.01), ("latents", torch.randn(9, 4, 2)), @@ -153,7 +154,9 @@ def emit_mean(self, *args, **kwargs): def context(student, rollout=0): - args = SimpleNamespace(hf_checkpoint="unused", pdd_num_intervals=32, pdd_block_size=4, seed=42) + args = SimpleNamespace( + hf_checkpoint="unused", pdd_num_intervals=32, pdd_block_size=4, seed=42, diffusion_model_family="qwen_image21" + ) return DiffusionLossContext( models={"transformer": student}, train_pipeline_config=Config(), @@ -167,7 +170,9 @@ def context(student, rollout=0): def rollout_pair(index): return dict( - sample_index=index, pdd_trajectory=torch.randn(33, 4, 2), denoising_env=SimpleNamespace(pos_cond_kwargs={}) + sample_index=index, + pdd_trajectory={"visual": torch.randn(33, 4, 2)}, + denoising_env=SimpleNamespace(pos_cond_kwargs={}), ) @@ -188,12 +193,12 @@ def test_eight_block_updates_from_rollout_states_match_an_independent_loop(): k = prepared.extras["selected"] x, sigma = prepared.latents["visual"], prepared.timesteps_for_model["visual"] assert prepared.extras["start"] == 4 * step <= k < 4 * step + 4 - torch.testing.assert_close(x[0], pair["pdd_trajectory"][4 * step], rtol=0, atol=0) + torch.testing.assert_close(x[0], pair["pdd_trajectory"]["visual"][4 * step], rtol=0, atol=0) # What the actor does: run the frozen teacher through the prepare hook's solver, without grad. with torch.no_grad(): target = prepared.teacher_solver(lambda lat, ts: {"visual": teacher(lat["visual"], ts["visual"])}) # The teacher starts from the rollout's state at the sampled interval. - torch.testing.assert_close(teacher.inputs[-2][0], pair["pdd_trajectory"][k], rtol=0, atol=0) + torch.testing.assert_close(teacher.inputs[-2][0], pair["pdd_trajectory"]["visual"][k], rtol=0, atol=0) loss = pdd_loss_formula( ctx, [pair], @@ -206,7 +211,7 @@ def test_eight_block_updates_from_rollout_states_match_an_independent_loop(): optim_step_idx=0, train_output_inputs=[], ) - x_k = pair["pdd_trajectory"][k].unsqueeze(0) + x_k = pair["pdd_trajectory"]["visual"][k].unsqueeze(0) expected = teacher_mean_velocity(lambda s, t: teacher(s, t.expand(1)), x_k, GRID[k], GRID.diff()[k]) refloss = interval_loss(reference(x, sigma), k, expected).sum() torch.testing.assert_close(loss, refloss, rtol=0, atol=0) @@ -246,7 +251,9 @@ def __init__(self): with torch.device("meta"): # non-zero ranks build the student on meta before FSDP sharding model = get_peft_model(Tiny(), LoraConfig(r=2, lora_alpha=2, target_modules=["to_q"])) # The loader's order: LoRA first, then the model-transform hook on the unwrapped model. - install_student(model.get_base_model(), SimpleNamespace(pdd_num_intervals=32)) + install_student( + model.get_base_model(), SimpleNamespace(diffusion_model_family="qwen_image21", pdd_num_intervals=32) + ) assert all(p.is_meta for p in model.parameters()) assert model.base_model.model.proj_out.parallel.weight.shape == (32, 2, 4) trainable = {name for name, p in model.named_parameters() if p.requires_grad} @@ -260,6 +267,115 @@ def __init__(self): assert {name for name in dict(model.named_parameters()) if state._saved(name)} == trainable +# --- MiniMax H3: video and audio streams ---------------------------------------------------------------- + + +def test_h3_grid_matches_the_sglang_schedule_and_its_blocks(): + # sgl-d's minimax_h3_time_shift_sigmas, in fp32: shift * t / (1 + (shift - 1) * t). + for shift in (12.0, 3.0): + grid = integration.h3_grid(32, shift) + base = torch.linspace(1.0, 0.0, 33, dtype=torch.float32) + assert torch.equal(grid, shift * base / (1 + (shift - 1) * base)) + # An 8-step request's block boundaries are every 4th point of the 32-interval grid. + torch.testing.assert_close(grid[::4], integration.h3_grid(8, shift), rtol=0, atol=1e-6) + + +def test_h3_rollout_splits_video_and_padded_audio_rows(): + videos, audios = 6, 3 + layout = {"update_mask": torch.ones(videos, dtype=torch.bool), "audio_pos": torch.arange(audios)} + env = SimpleNamespace(pos_cond_kwargs=SimpleNamespace(h3_packed_layout=layout)) + video, audio = torch.randn(33, videos, 96), torch.randn(33, audios, 32) + packed = torch.cat((video, nn.functional.pad(audio, (0, 64))), dim=1) + split = integration.PDD_FAMILIES["h3"].split_states + streams = split(packed, env) + assert torch.equal(streams["visual"], video) and torch.equal(streams["audio"], audio) + with pytest.raises(ValueError): + split(packed[:, 1:], env) + packed[:, -1, 40] = 1.0 + with pytest.raises(ValueError): + split(packed, env) + + +def test_h3_student_gets_video_and_audio_heads(): + model = nn.Module() + model.proj_out, model.audio_proj_out = nn.Linear(8, 4), nn.Linear(8, 2) + install_student(model, SimpleNamespace(diffusion_model_family="h3", pdd_num_intervals=32)) + assert model.proj_out.parallel.weight.shape == (32, 4, 8) + assert model.audio_proj_out.parallel.weight.shape == (32, 2, 8) + assert model.proj_out(torch.randn(1, 5, 8)).shape == (1, 5, 32 * 4) + + +def test_h3_streams_share_one_interval_and_one_joint_teacher_call(): + from miles.backends.fsdp_utils.metrics import SCHEMA + + torch.manual_seed(5) + heads = {"visual": ParallelLinear(nn.Linear(2, 2), 32), "audio": ParallelLinear(nn.Linear(2, 2), 32)} + args = SimpleNamespace( + diffusion_model_family="h3", + pdd_num_intervals=32, + pdd_block_size=4, + seed=42, + diffusion_flow_shift=12.0, + diffusion_audio_flow_shift=3.0, + ) + ctx = DiffusionLossContext( + models={"transformer": nn.Identity()}, + train_pipeline_config=Config(), + sde_backend=None, + device=torch.device("cpu"), + forward_dtype=torch.float32, + args=args, + rollout_id=3, + ) + trajectory = {"visual": torch.randn(33, 4, 2), "audio": torch.randn(33, 3, 2)} + pair = dict( + sample_index=1, pdd_start=8, pdd_trajectory=trajectory, denoising_env=SimpleNamespace(pos_cond_kwargs={}) + ) + prepared = prepare_pdd_batch(ctx, [pair], microbatch_id=0, optim_step_idx=0) + grids, k = prepared.extras["grids"], prepared.extras["selected"] + assert prepared.pos_cond["h3_target_has_soundtrack"] is True + assert torch.equal(grids["visual"], integration.h3_grid(32, 12.0)) + assert torch.equal(grids["audio"], integration.h3_grid(32, 3.0)) + for stream in heads: + assert torch.equal(prepared.latents[stream][0], trajectory[stream][8]) + assert torch.equal(prepared.timesteps_for_model[stream], grids[stream][8].reshape(1) * 1000) + + calls = [] + + def forward(latents, timesteps): + calls.append({stream: float(t) for stream, t in timesteps.items()}) + return {stream: 0.5 * x + timesteps[stream] / 1000 for stream, x in latents.items()} + + target = prepared.teacher_solver(forward) + # One joint teacher call per midpoint stage, each stream at its own grid sigma. + assert len(calls) == 2 and calls[0] == {s: float(grids[s][k] * 1000) for s in heads} + for stream in heads: + expected = teacher_mean_velocity( + lambda x, t: 0.5 * x + t, trajectory[stream][k].unsqueeze(0), grids[stream][k], grids[stream].diff()[k] + ) + torch.testing.assert_close(target[stream], expected) + + class SchemaMetrics: + def emit_mean(self, name, *, total, count): + assert name in SCHEMA, name + + predictions = {stream: head(prepared.latents[stream]) for stream, head in heads.items()} + loss = pdd_loss_formula( + ctx, + [pair], + prepared, + new_pred={stream: p.permute(1, 2, 0, 3).flatten(2) for stream, p in predictions.items()}, + old_pred=None, + ref_pred=None, + teacher_pred=target, + metrics=SchemaMetrics(), + optim_step_idx=0, + train_output_inputs=[], + ) + expected = sum(interval_loss(predictions[s], k, target[s]) for s in heads).sum() + torch.testing.assert_close(loss, expected, rtol=0, atol=0) + + # --- arguments ----------------------------------------------------------------------------------------- @@ -332,6 +448,38 @@ def test_defaults_select_the_sglang_rollout_and_eight_updates_per_rollout(): ) +H3_ARGS = dict( + diffusion_model_family="h3", + diffusion_task="t2va", + sglang_dit_precision="bf16", + diffusion_flow_shift=12.0, + diffusion_audio_flow_shift=3.0, + sglang_tp_size=1, + sglang_sp_degree=1, + colocate=False, + lora_ipc_weight_sync=False, +) + + +def test_h3_defaults_keep_the_family_fsdp_plan_and_select_its_patch_group(): + args = configured(**H3_ARGS) + assert args.fsdp_param_dtype is None and args.rollout_patch_groups == ["pdd_h3"] + + +@pytest.mark.parametrize( + "name,value", + [ + ("sglang_dit_precision", "fp32"), + ("diffusion_audio_flow_shift", None), + ("sglang_tp_size", 2), + ("diffusion_task", "t2i"), + ], +) +def test_h3_unvalidated_modes_fail(name, value): + with pytest.raises(ValueError): + configured(**{**H3_ARGS, name: value}) + + @pytest.mark.parametrize( "name,value", [ From 5571eb8aafcc0f75759b80eceb1bf75b3828103a Mon Sep 17 00:00:00 2001 From: niehen6174 <1639206518@qq.com> Date: Mon, 16 Nov 2026 23:38:14 +0800 Subject: [PATCH 2/2] fix(pdd): check H3's audio grid against the trainer; test the H3 engine side - The pdd_h3 patch appends the engine's audio sigma grid to the recorded video grid, and the converter checks every stream's grid against the trainer's bit for bit (a family's split_sigmas cuts the recorded grid into streams). Before, only the video grid was checked, so an engine audio schedule that drifted from --diffusion-audio-flow-shift would have trained against misplaced teacher targets without an error. - Factor the head-cache lookup (heads_at) and the audio packing (pack_audio) out of the patch closures and cover them on CPU: the cached [rows, N*C] layout yields head k, and a packed trajectory round-trips through the converter. - Docs: the unweighted sum of per-stream losses, the stream metric names, and the one-request-per-engine assumption of the block cache. --- docs/developer/pdd.md | 13 ++++-- .../monkey_patches/patch_pdd_h3.py | 46 +++++++++++++------ miles/distillation/integration.py | 16 ++++++- miles/rollout/pdd_rollout.py | 7 +-- tests/fast/distillation/test_pdd.py | 38 +++++++++++++++ 5 files changed, 96 insertions(+), 24 deletions(-) diff --git a/docs/developer/pdd.md b/docs/developer/pdd.md index 3f4880cd4..ae224d40b 100644 --- a/docs/developer/pdd.md +++ b/docs/developer/pdd.md @@ -80,7 +80,8 @@ are disabled because they are verified only for BF16 engine weights. every fourth point of H3's shifted grid, as for a native 8-step request). The native rollout collector records video target rows; the patch also records the audio rows after each step and appends them, zero-padded to the video width, to the trajectory, -which the family's `split_states` cuts back apart. Native fused PDD heads +which the family's `split_states` cuts back apart. It also appends the engine's audio grid +to the recorded video grid, and the converter checks both against the trainer's grids. Native fused PDD heads (`pdd_fused_heads`) are rejected: training needs the live, unfused heads. ## Train and resume @@ -157,9 +158,13 @@ PDD uses the standard FSDP checkpoint (model, optimizer, scheduler, RNG, dataset cursor), written at rollout boundaries; interval selection is a hash of seed, rollout, lane and block, so it does not depend on RNG state. -`train/pdd_next_latent_mae` and `train/pdd_update_relative_error` (H3 also -`train/pdd_audio_*` and the per-stream `train/pdd_{visual,audio}_loss`) compare the -trainer's next block state with the one SGLang recorded. Block 0 measures pure +`train/pdd_next_latent_mae` and `train/pdd_update_relative_error` compare the +trainer's next block state with the one SGLang recorded. They keep their Qwen names for +the video stream; H3 adds `train/pdd_audio_next_latent_mae` and +`train/pdd_audio_update_relative_error`, and logs each stream's share of `train/loss` as +`train/pdd_visual_loss` / `train/pdd_audio_loss`. The streams' per-element mean interval +losses are summed without weights; H3's audio loss is about 30× smaller than its video +loss, so the video stream dominates the gradient. Block 0 measures pure engine/trainer parity; later blocks also include rollout staleness. ## Verification and limits diff --git a/miles/backends/sglang_diffusion_utils/monkey_patches/patch_pdd_h3.py b/miles/backends/sglang_diffusion_utils/monkey_patches/patch_pdd_h3.py index 6e4251b5a..ce14fdd46 100644 --- a/miles/backends/sglang_diffusion_utils/monkey_patches/patch_pdd_h3.py +++ b/miles/backends/sglang_diffusion_utils/monkey_patches/patch_pdd_h3.py @@ -4,8 +4,11 @@ 32 intervals of the shifted grids (one per H3 grid point of a 32-step request): the first interval of each block runs the DiT and caches every head, the block's other three step on the cache without a forward. The rollout trajectory returns each interval's start state of -both streams: video target rows, then audio rows zero-padded to the video width, which the -trainer's ``split_states`` cuts back apart. +both streams: video target rows, then audio rows zero-padded to the video width; its sigmas +are the video grid followed by the audio grid. The trainer's family hooks cut both back apart. + +The block cache lives on the model, so an engine must run one request at a time (PDD validates +one GPU per engine and rollout microgroup size 1). """ import torch @@ -27,6 +30,27 @@ def forward(self, hidden): return self.parallel(hidden).permute(1, 0, 2).flatten(1), None +def heads_at(block, step_index): + """Interval ``step_index``'s prediction from a block's cached [rows, N*C] head output.""" + return block.unflatten(-1, (INTERVALS, -1))[:, step_index].contiguous() + + +def pack_audio(trajectory, audio_steps, audio_sigmas): + """Append the recorded audio rows (zero-padded to the video width) and the audio grid to the trajectory.""" + video = trajectory.latents + if trajectory.latent_step_indices.tolist() != list(range(len(audio_steps))): + raise ValueError("H3 PDD needs the full trajectory of both streams") + if len(audio_sigmas) != len(audio_steps): + raise ValueError("H3 PDD audio grid and audio states differ in length") + audio = torch.stack(audio_steps).to(video.dtype).unsqueeze(0) + padded = audio.new_zeros(*audio.shape[:-1], video.shape[-1]) + padded[..., : audio.shape[-1]] = audio + trajectory.latents = torch.cat((video, padded), dim=2) + audio_sigmas = torch.tensor([float(s) for s in audio_sigmas], dtype=trajectory.sigmas.dtype) + trajectory.sigmas = torch.cat((trajectory.sigmas, audio_sigmas)) + return trajectory + + def apply(): from sglang.multimodal_gen.runtime.distributed import get_sp_world_size, get_tp_world_size from sglang.multimodal_gen.runtime.models.dits.minimax_h3 import MiniMaxH3DiTModel @@ -68,9 +92,9 @@ def timesteps(self, batch, server_args): def forward_dit(self, model, call_kwargs, step_index, **kwargs): if step_index % BLOCK == 0: video, audio = original_forward(self, model, call_kwargs, step_index, **kwargs) - model._miles_pdd_block = (video.unflatten(-1, (INTERVALS, -1)), audio.unflatten(-1, (INTERVALS, -1))) + model._miles_pdd_block = (video, audio) video, audio = model._miles_pdd_block - return video[:, step_index].contiguous(), audio[:, step_index].contiguous() + return heads_at(video, step_index), heads_at(audio, step_index) def loop(*, positive, initial_audio_rows, on_step=None, rollout_ctx=None, **kwargs): if rollout_ctx is None: @@ -78,6 +102,7 @@ def loop(*, positive, initial_audio_rows, on_step=None, rollout_ctx=None, **kwar audio_target = positive.audio_target_slice collector = rollout_ctx.collector collector.audio_steps = [initial_audio_rows[audio_target].detach().float().cpu().clone()] + collector.audio_sigmas = list(kwargs["sigmas_audio"]) def record(step, video_rows, audio_rows): # Called after both streams moved, so this is the audio state at interval step + 1. @@ -95,17 +120,8 @@ def record(step, video_rows, audio_rows): def build(self): data = original_build(self) - audio = getattr(self, "audio_steps", None) - if audio is None: - return data - trajectory = data.dit_trajectory - video = trajectory.latents - if trajectory.latent_step_indices.tolist() != list(range(len(audio))): - raise ValueError("H3 PDD needs the full trajectory of both streams") - audio = torch.stack(audio).to(video.dtype).unsqueeze(0) - padded = audio.new_zeros(*audio.shape[:-1], video.shape[-1]) - padded[..., : audio.shape[-1]] = audio - trajectory.latents = torch.cat((video, padded), dim=2) + if getattr(self, "audio_steps", None) is not None: + pack_audio(data.dit_trajectory, self.audio_steps, self.audio_sigmas) return data MiniMaxH3DiTModel.post_load_weights = post_load diff --git a/miles/distillation/integration.py b/miles/distillation/integration.py index 7ec6b62cc..f028be1d9 100644 --- a/miles/distillation/integration.py +++ b/miles/distillation/integration.py @@ -96,8 +96,9 @@ class PDDFamily: ``heads`` maps each latent stream to the Diffusers transformer's output layer that becomes N heads; ``grids(args)`` gives each stream's (N+1)-point sigma grid; ``model_time`` / ``teacher_time`` turn a grid - sigma into the student's and the teacher's ``timesteps_for_model``; ``split_states`` cuts the rollout's - per-interval states into streams; ``validate`` checks the family's rollout settings. + sigma into the student's and the teacher's ``timesteps_for_model``; ``split_states`` / ``split_sigmas`` cut + the rollout's per-interval states and recorded grid into streams; ``validate`` checks the family's + rollout settings. Streams share one loss; each contributes its per-element mean interval loss. """ task: str @@ -110,6 +111,7 @@ class PDDFamily: model_time: Callable[[Any, str, torch.Tensor], torch.Tensor] teacher_time: Callable[[Any, str, torch.Tensor], torch.Tensor] split_states: Callable[[torch.Tensor, Any], dict[str, torch.Tensor]] + split_sigmas: Callable[[torch.Tensor], dict[str, torch.Tensor]] validate: Callable[[Any], None] cond_extras: dict[str, Any] = field(default_factory=dict) @@ -130,6 +132,14 @@ def _h3_split_states(states, env): return {"visual": states[:, :videos], "audio": states[:, videos:, :H3_AUDIO_CHANNELS]} +def _h3_split_sigmas(sigmas): + """The H3 rollout records the video grid followed by the audio grid.""" + if sigmas.ndim != 1 or len(sigmas) % 2: + raise ValueError("H3 PDD rollout must record the video and audio grids") + video, audio = sigmas.chunk(2) + return {"visual": video, "audio": audio} + + def _h3_validate(args): if args.diffusion_flow_shift is None or args.diffusion_audio_flow_shift is None: raise ValueError("H3 PDD requires --diffusion-flow-shift and --diffusion-audio-flow-shift for its grids") @@ -150,6 +160,7 @@ def _h3_validate(args): model_time=lambda args, stream, sigma: embedded_sigmas(engine_timesteps(sigma)), teacher_time=lambda args, stream, sigma: sigma, split_states=lambda states, env: {"visual": states}, + split_sigmas=lambda sigmas: {"visual": sigmas}, validate=_qwen_validate, ), "h3": PDDFamily( @@ -166,6 +177,7 @@ def _h3_validate(args): model_time=lambda args, stream, sigma: sigma * 1000.0, teacher_time=lambda args, stream, sigma: sigma * 1000.0, split_states=_h3_split_states, + split_sigmas=_h3_split_sigmas, validate=_h3_validate, # Audio rows are PDD targets: the H3 forward returns their prediction only for a soundtrack target. cond_extras={"h3_target_has_soundtrack": True}, diff --git a/miles/rollout/pdd_rollout.py b/miles/rollout/pdd_rollout.py index bcfb94963..c8a0ddbb2 100644 --- a/miles/rollout/pdd_rollout.py +++ b/miles/rollout/pdd_rollout.py @@ -21,15 +21,16 @@ async def no_reward(args, samples, **kwargs): def convert_samples_to_train_data(args, samples): family = pdd_family(args) - # The rollout records its trajectory on the video grid; H3's audio grid only differs in shift. - grid = family.grids(args)["visual"] + grids = family.grids(args) states_count = args.pdd_num_intervals + 1 pairs = [] for sample in samples: traj, env = sample.dit_trajectory, sample.denoising_env if traj is None or env is None or env.pos_cond_kwargs is None: raise ValueError("PDD requires SGLang trajectory and positive conditioning") - if traj.sigmas is None or not torch.equal(traj.sigmas.cpu().float(), grid): + # Every stream's recorded grid must equal the trainer's, bit for bit. + sigmas = family.split_sigmas(traj.sigmas.cpu().float()) if traj.sigmas is not None else {} + if set(sigmas) != set(grids) or not all(torch.equal(sigmas[s], grids[s]) for s in grids): raise ValueError("PDD rollout sigma grid differs from training") # Require every interval start + the endpoint, never silently index a # filtered trajectory as if it were a complete one. diff --git a/tests/fast/distillation/test_pdd.py b/tests/fast/distillation/test_pdd.py index 5ce4962d7..8b306f0ae 100644 --- a/tests/fast/distillation/test_pdd.py +++ b/tests/fast/distillation/test_pdd.py @@ -296,6 +296,44 @@ def test_h3_rollout_splits_video_and_padded_audio_rows(): split(packed, env) +def test_h3_engine_heads_and_packed_rollout_round_trip_through_the_converter(): + """The engine side of pdd_h3 without sglang: the cached head layout, then the packed trajectory.""" + from miles.backends.sglang_diffusion_utils.monkey_patches.patch_pdd_h3 import PDDHeads, heads_at, pack_audio + + torch.manual_seed(3) + heads = PDDHeads(nn.Linear(8, 6)) + hidden = torch.randn(5, 8) + block, bias = heads(hidden) + assert bias is None and block.shape == (5, 32 * 6) + for k in (0, 5, 31): + torch.testing.assert_close(heads_at(block, k), heads.parallel(hidden)[k], rtol=0, atol=0) + + videos, audios = 6, 3 + video, audio = torch.randn(33, videos, 96), torch.randn(33, audios, 32) + grids = {"visual": integration.h3_grid(32, 12.0), "audio": integration.h3_grid(32, 3.0)} + trajectory = SimpleNamespace( + latents=video.unsqueeze(0), sigmas=grids["visual"].clone(), latent_step_indices=torch.arange(33) + ) + pack_audio(trajectory, list(audio), grids["audio"].tolist()) + layout = {"update_mask": torch.ones(videos, dtype=torch.bool), "audio_pos": torch.arange(audios)} + sample = SimpleNamespace( + index=4, + denoising_env=SimpleNamespace(pos_cond_kwargs=SimpleNamespace(h3_packed_layout=layout)), + dit_trajectory=SimpleNamespace( + sigmas=trajectory.sigmas, latents=trajectory.latents[0], latent_step_indices=trajectory.latent_step_indices + ), + ) + args = SimpleNamespace( + diffusion_model_family="h3", pdd_num_intervals=32, diffusion_flow_shift=12.0, diffusion_audio_flow_shift=3.0 + ) + streams = pdd_rollout.convert_samples_to_train_data(args, [sample])["train_data"][0]["pdd_trajectory"] + assert torch.equal(streams["visual"], video) and torch.equal(streams["audio"], audio) + # An engine whose audio schedule drifted from the trainer's grid is rejected. + args.diffusion_audio_flow_shift = 4.0 + with pytest.raises(ValueError, match="sigma grid"): + pdd_rollout.convert_samples_to_train_data(args, [sample]) + + def test_h3_student_gets_video_and_audio_heads(): model = nn.Module() model.proj_out, model.audio_proj_out = nn.Linear(8, 4), nn.Linear(8, 2)