Skip to content
Closed
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
134 changes: 134 additions & 0 deletions docs/developer/pdd.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
# 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,
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.
- 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,
`--sglang-lora-merge-mode dynamic`): merging it into BF16 weights rounds most of a
small adapter update away and drifts from the trainer's forward.
- FSDP with SP = 1, microbatch = 1, eight optimizer updates per rollout.
- SGLang engines with one GPU each, TP = SP = 1, deterministic 8-step ODE rollout,
one sample per request, CFG = 1.
- 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.

## 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.
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
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
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.

`--loss-type pdd` registers its prepare/loss/train-input hooks in the loss hub
(`LOSS_HOOKS[("pdd", "actor")]`) and fills defaults for generic Miles hooks
(`set_pdd_defaults` in `miles/distillation/integration.py`); the trainer has no PDD
branches:

| Hook | PDD default |
|---|---|
| `--custom-train-model-transform-path` | `install_student`: `proj_out` 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` |

`validate_pdd_args` then rejects any configuration outside the validated scope.

### Rollout patch group

`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
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.

## Train and resume

### Qwen-Image 2.1, validated on 2 × H200 with colocated training and rollout

```bash
export PYTHONPATH=.
export MODEL=/path/to/qwen-image-2.1-snapshot
export PROMPTS=/path/to/train.jsonl
export OUTPUT=/scratch/pdd/run
python train_diffusion.py \
--loss-type pdd --train-backend fsdp \
--hf-checkpoint "$MODEL" --sglang-model-id Qwen-Image-2.1 \
--diffusion-model-family qwen_image21 --diffusion-task t2i \
--prompt-data "$PROMPTS" --input-key input \
--rollout-batch-size 8 --n-samples-per-prompt 1 --num-steps-per-rollout 8 \
--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-height 1024 --diffusion-width 1024 \
--diffusion-num-steps 8 --diffusion-eval-num-steps 8 \
--diffusion-sde-type ode --diffusion-noise-level 0 \
--diffusion-guidance-scale 1 --diffusion-true-cfg-scale 1 \
--use-lora --lora-rank 64 --lora-alpha 128 --lora-ipc-weight-sync --sglang-lora-merge-mode dynamic \
--lr 2e-5 --weight-decay 0 --adam-beta2 0.999 --seed 42 \
--sglang-dit-precision fp32 --use-miles-router --update-weight-buffer-size 1073741824 \
--actor-num-gpus-per-node 2 --num-gpus-per-node 2 \
--rollout-num-gpus 2 --rollout-num-gpus-per-engine 1 --colocate \
--save "$OUTPUT/ckpt" --save-interval 100
```

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.

To resume, rerun the command with `--load "$OUTPUT/ckpt"` and a larger
`--num-rollout`, keeping the model, data and training configuration unchanged.
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
trainer's next block state with the one SGLang recorded. Block 0 measures pure
engine/trainer parity; later blocks also include rollout staleness.

## Verification and limits

```bash
python -m pytest tests/fast/distillation/test_pdd.py
python -m pytest tests/fast-gpu/backends/sglang_diffusion_utils/test_pdd_sglang_loop.py
```

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
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.

These are correctness checks, not quality claims. Automatic image/video metrics,
historical datasets/reports and experiment orchestration are outside this change.
5 changes: 4 additions & 1 deletion docs/user-guide/cli-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,9 @@ For how these batch arguments relate to each other, see

| Flag | Default | What |
|---|---|---|
| `--diffusion-forward-dtype` | `bf16` | Training-side DiT compute — FSDP `param_dtype` and the input cast. It reaches the engine only as the LoRA-merge precision (`fp32` merges in fp32, see [LoRA](../advanced/lora.md)); the engine's DiT precision is `--sglang-dit-precision`, which is not derived from it — set both to the same value. |
| `--diffusion-forward-dtype` | `bf16` | Training-side DiT compute — the input cast and, unless `--fsdp-param-dtype` is set, FSDP `param_dtype`. It reaches the engine only as the LoRA-merge precision (`fp32` merges in fp32, see [LoRA](../advanced/lora.md)); the engine's DiT precision is `--sglang-dit-precision`, which is not derived from it — set both to the same value. |
| `--fsdp-master-dtype` | `fp32` | Sharded master weights and optimizer state. |
| `--fsdp-param-dtype` | `--diffusion-forward-dtype` | Parameter all-gather (FSDP `param_dtype`); `fp32` keeps gathered weights at master precision and leaves matmuls to autocast. |
| `--fsdp-reduce-dtype` | `fp32` | Gradient reduce-scatter. |

See [Dtype Control](../advanced/dtype-control.md).
Expand Down Expand Up @@ -136,6 +137,7 @@ See [Dtype Control](../advanced/dtype-control.md).
| `--train-backend` | enum | `fsdp` | Only value. |
| `--fsdp-master-dtype` | enum | `fp32` | `fp32` / `bf16` / `fp16`. Load, shard, and optimizer-state precision. |
| `--fsdp-reduce-dtype` | enum | `fp32` | `bf16` matches flow_grpo's all-bf16 policy but adds cross-rank add-noise. |
| `--fsdp-param-dtype` | enum | – | `fp32` / `bf16` / `fp16`; defaults to `--diffusion-forward-dtype`. |
| `--diffusion-forward-dtype` | enum | `bf16` | `bf16` / `fp16` / `fp32`. |
| `--fsdp-cpu-offload` | flag | off | Offloads params, grads, optimizer state; the optimizer then runs on CPU. |
| `--fsdp-cpu-backend` | str | `gloo` | CPU process group for the above. |
Expand Down Expand Up @@ -279,6 +281,7 @@ See [Dtype Control](../advanced/dtype-control.md).
| `--teacher-cpu-offload` | flag | off | Keep the teacher shards in pinned CPU memory between forwards. |
| `--custom-prepare-train-batch-path` | str | – | `custom_loss` only: builds DiT inputs. |
| `--custom-loss-function-path` | str | – | `custom_loss` only: loss **formula** only — the DiT forward stays in the actor. |
| `--custom-train-model-transform-path` | str | – | `fn(model, args)` edits each trainable component in place after loading and LoRA, before FSDP wrapping (meta-initialized on non-zero ranks); parameters it adds train in full beside the adapters and are kept in LoRA checkpoints. |
| `--custom-train-input-postprocess-path` | str | – | `custom_loss` only: preprocesses a rank's train pairs (the converted rollout output) before they are split into micro-batches, and returns the pairs to train on. `ctx.external_data` holds earlier trainer groups' outputs. |
| `--custom-train-output-function-path` | str | – | `custom_loss` only: runs without grad after a rollout's train steps; its return value reaches the paired rank of each later trainer group as `ctx.external_data[<role>]`. |
| `--diffusion-nft-beta` | float | `1.0` | |
Expand Down
25 changes: 21 additions & 4 deletions miles/backends/fsdp_utils/actor.py
Original file line number Diff line number Diff line change
Expand Up @@ -540,6 +540,8 @@ def _forward_train_pair_batch(
def _compute_noise_pred(
model,
*,
latents: dict[str, torch.Tensor] = latents_in,
timesteps: dict[str, torch.Tensor] = timesteps_in,
use_cfg: bool = prepared.use_cfg,
cfg_batching: bool = prepared.cfg_batching,
guidance_scale: float = prepared.guidance_scale,
Expand All @@ -552,8 +554,8 @@ def _compute_noise_pred(
):
return train_pipeline_config.compute_noise_pred(
model=model,
latents_input=latents_in,
timesteps_input=timesteps_in,
latents_input=latents,
timesteps_input=timesteps,
pos_cond=pos_cond_in,
neg_cond=neg_cond_in,
joint_cond=joint_cond_in,
Expand All @@ -570,14 +572,29 @@ def _compute_noise_pred(
raise ValueError("the prepared batch asks for a teacher forward, which needs --teacher-load")
teacher = self.teacher_models[prepared.component_name]
use_cfg = prepared.teacher_guidance_scale > 1.0
with torch.no_grad():
teacher_pred = _compute_noise_pred(

def teacher_forward(latents=latents_in, timesteps=timesteps_in):
if latents is not latents_in:
latents, timesteps, _ = apply_input_dtype_policy(
train_pipeline_config.input_dtype_policy,
latents=latents,
timesteps=timesteps,
conds=(None, None, None),
default_dtype=forward_dtype,
)
return _compute_noise_pred(
teacher,
latents=latents,
timesteps=timesteps,
use_cfg=use_cfg,
cfg_batching=use_cfg and train_pipeline_config.cfg_batching,
guidance_scale=prepared.teacher_guidance_scale,
true_cfg_scale=None,
)

with torch.no_grad():
solver = prepared.teacher_solver
teacher_pred = teacher_forward() if solver is None else solver(teacher_forward)
# A no-grad forward leaves FSDP's root parameters gathered; sleep must move the shards.
reshard_model(teacher)

Expand Down
15 changes: 11 additions & 4 deletions miles/backends/fsdp_utils/checkpoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,17 +70,24 @@ def _is_lora_param_name(name: str) -> bool:


class ModelState(Stateful):
"""Wrapper for model state. ``lora_only=True`` saves/loads only LoRA
adapter weights; base weights come from ``args.hf_checkpoint`` on init."""
"""Wrapper for model state. ``lora_only=True`` saves/loads only the LoRA adapter weights and any
parameter trained in full beside them (e.g. a layer the model-transform hook added); frozen base
weights come from ``args.hf_checkpoint`` on init."""

def __init__(self, model, lora_only: bool = False):
self.model = model
self.lora_only = lora_only
self.trained_in_full = {
name for name, param in model.named_parameters() if param.requires_grad and not _is_lora_param_name(name)
}

def _saved(self, name: str) -> bool:
return _is_lora_param_name(name) or name in self.trained_in_full

def state_dict(self):
model_state_dict, _ = get_state_dict(self.model, optimizers=[])
if self.lora_only:
model_state_dict = {k: v for k, v in model_state_dict.items() if _is_lora_param_name(k)}
model_state_dict = {k: v for k, v in model_state_dict.items() if self._saved(k)}
return {"model": model_state_dict}

def load_state_dict(self, state_dict):
Expand All @@ -94,7 +101,7 @@ def load_state_dict(self, state_dict):
)
# strict=False swallows mismatches; lora_only expects missing base keys, anything else is a bad checkpoint
unclaimed = list(incompatible.unexpected_keys)
unfilled = [k for k in incompatible.missing_keys if not self.lora_only or _is_lora_param_name(k)]
unfilled = [k for k in incompatible.missing_keys if not self.lora_only or self._saved(k)]
if unclaimed or unfilled:
logger.error(
f"[FSDP] Checkpoint mismatch: {len(unclaimed)} unclaimed checkpoint keys, "
Expand Down
21 changes: 15 additions & 6 deletions miles/backends/fsdp_utils/diffusion_update_weight_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,10 @@ def _iter_buckets(self, target_module: str) -> Iterator[list[tuple[str, torch.Te
return self.hf_weight_iterators[target_module].iter_hf_weights()

@abc.abstractmethod
def update_bucket_weights(self, named_tensors: list[tuple[str, torch.Tensor]], target_module: str) -> None:
pass
def update_bucket_weights(
self, named_tensors: list[tuple[str, torch.Tensor]], target_module: str, *, replace_weights: bool = False
) -> None:
"""``replace_weights`` sends plain weights even from a LoRA updater (its full-trained parameters)."""


class DiffusionUpdateWeightFromTensor(DiffusionUpdateWeight):
Expand Down Expand Up @@ -107,7 +109,9 @@ def connect_rollout_engines(
# Calculate TP rank within this SGLang engine group.
self.tp_rank = dist.get_rank() - start_rank

def update_bucket_weights(self, named_tensors: list[tuple[str, torch.Tensor]], target_module: str) -> None:
def update_bucket_weights(
self, named_tensors: list[tuple[str, torch.Tensor]], target_module: str, *, replace_weights: bool = False
) -> None:
monkey_patch_torch_reductions()
logger.info("Using flattened tensor bucket (diffusion updater, module=%s)", target_module)
named_tensors_by_dtypes = {}
Expand Down Expand Up @@ -160,7 +164,7 @@ def update_bucket_weights(self, named_tensors: list[tuple[str, torch.Tensor]], t
"target_modules": [target_module],
"weight_version": str(self.weight_version),
}
if self.sgl_d_weight_update_mode is not None:
if self.sgl_d_weight_update_mode is not None and not replace_weights:
model = self.models[target_module]
adapter_config = model.peft_config[model.active_adapter]
kwargs["weight_update_mode"] = self.sgl_d_weight_update_mode
Expand Down Expand Up @@ -264,6 +268,9 @@ def _update_component_weights(self, target_module: str) -> None:
)
if num_lora_tensors == 0:
logger.error("LoRA weight sync [%s]: no lora tensors found in training state_dict", target_module)
# Parameters trained in full beside the adapter replace the rollout's weights.
for bucket in self.hf_weight_iterators[target_module].iter_hf_trained_weights():
self.update_bucket_weights(bucket, target_module, replace_weights=True)


class DiffusionUpdateWeightFromTensorLoRAIPC(DiffusionUpdateWeightLoRA, DiffusionUpdateWeightFromTensor):
Expand Down Expand Up @@ -351,11 +358,13 @@ def connect_rollout_engines(self, rollout_engines, rollout_engine_lock):
timeout=timedelta(minutes=self.args.distributed_timeout_minutes),
)

def update_bucket_weights(self, named_tensors: list[tuple[str, torch.Tensor]], target_module: str) -> None:
def update_bucket_weights(
self, named_tensors: list[tuple[str, torch.Tensor]], target_module: str, *, replace_weights: bool = False
) -> None:
if dist.get_rank() != 0:
return
lora_kwargs = {}
if self.sgl_d_weight_update_mode is not None:
if self.sgl_d_weight_update_mode is not None and not replace_weights:
model = self.models[target_module]
adapter_config = model.peft_config[model.active_adapter]
lora_kwargs = dict(
Expand Down
14 changes: 12 additions & 2 deletions miles/backends/fsdp_utils/hf_weight_iterator.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,12 @@ def __init__(self, *args, **kwargs):
for adapter in module.lora_A
}

def _iter_hf_param_units(self) -> Iterator[list[tuple[str, torch.Tensor]]]:
weights = ((name, param) for name, param in self.model.state_dict().items() if "lora_" not in name)
def _iter_hf_param_units(self, names: set[str] | None = None) -> Iterator[list[tuple[str, torch.Tensor]]]:
weights = (
(name, param)
for name, param in self.model.state_dict().items()
if "lora_" not in name and (names is None or name in names)
)
for name, full in self._iter_full_params(weights):
if name in self._lora_by_base_weight:
lora_A, lora_B, scaling = self._lora_by_base_weight[name]
Expand All @@ -48,6 +52,12 @@ def _iter_hf_param_units(self) -> Iterator[list[tuple[str, torch.Tensor]]]:
expand = get_param_transform(hf_name, full, self.diffusion_model_family)
yield [(hf_name, full)] if expand is None else list(expand(hf_name, full, self.model))

def _iter_hf_trained_units(self) -> Iterator[list[tuple[str, torch.Tensor]]]:
trained = {
name for name, param in self.model.named_parameters() if param.requires_grad and "lora_" not in name
}
return self._iter_hf_param_units(trained) if trained else iter(())

def _iter_hf_adapter_units(self) -> Iterator[list[tuple[str, torch.Tensor]]]:
"""One unit per LoRA module: sglang-d's lora_merge applies its lora_A and lora_B as a pair."""
halves_by_module: dict[str, list[tuple[str, torch.Tensor]]] = {}
Expand Down
Loading
Loading