Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
97 changes: 77 additions & 20 deletions docs/developer/pdd.md
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
# 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
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,
Expand All @@ -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.

Expand All @@ -51,24 +57,33 @@ 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. 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

### Qwen-Image 2.1, validated on 2 × H200 with colocated training and rollout
Expand Down Expand Up @@ -98,6 +113,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 <dir>`, and run 8 steps
with `--lora-path <adapter> --lora-merge-mode dynamic` and
`SGLANG_DIFFUSION_MINIMAX_H3_PDD_HEADS=<dir>/pdd_fused_heads.safetensors`.

Optionally add `--eval-prompt-data <name> <jsonl> --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.
Expand All @@ -109,7 +159,12 @@ 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
trainer's next block state with the one SGLang recorded. Block 0 measures pure
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
Expand All @@ -122,13 +177,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.
85 changes: 54 additions & 31 deletions miles/backends/fsdp_utils/loss_hub/pdd.py
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -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,
Expand All @@ -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,
)
Expand All @@ -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()
4 changes: 4 additions & 0 deletions miles/backends/fsdp_utils/metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 (
Expand Down
Loading
Loading