diff --git a/docs/developer/pdd.md b/docs/developer/pdd.md new file mode 100644 index 000000000..beee72e55 --- /dev/null +++ b/docs/developer/pdd.md @@ -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 --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. diff --git a/docs/user-guide/cli-reference.md b/docs/user-guide/cli-reference.md index e249f433a..10cd2b738 100644 --- a/docs/user-guide/cli-reference.md +++ b/docs/user-guide/cli-reference.md @@ -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). @@ -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. | @@ -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[]`. | | `--diffusion-nft-beta` | float | `1.0` | | diff --git a/miles/backends/fsdp_utils/actor.py b/miles/backends/fsdp_utils/actor.py index b948f444c..42ebdb894 100644 --- a/miles/backends/fsdp_utils/actor.py +++ b/miles/backends/fsdp_utils/actor.py @@ -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, @@ -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, @@ -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) diff --git a/miles/backends/fsdp_utils/checkpoint.py b/miles/backends/fsdp_utils/checkpoint.py index ff88c4d35..bb86c2c02 100644 --- a/miles/backends/fsdp_utils/checkpoint.py +++ b/miles/backends/fsdp_utils/checkpoint.py @@ -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): @@ -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, " diff --git a/miles/backends/fsdp_utils/diffusion_update_weight_utils.py b/miles/backends/fsdp_utils/diffusion_update_weight_utils.py index 1cb383255..24bde08d6 100644 --- a/miles/backends/fsdp_utils/diffusion_update_weight_utils.py +++ b/miles/backends/fsdp_utils/diffusion_update_weight_utils.py @@ -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): @@ -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 = {} @@ -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 @@ -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): @@ -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( diff --git a/miles/backends/fsdp_utils/hf_weight_iterator.py b/miles/backends/fsdp_utils/hf_weight_iterator.py index ffffe5e45..902929342 100644 --- a/miles/backends/fsdp_utils/hf_weight_iterator.py +++ b/miles/backends/fsdp_utils/hf_weight_iterator.py @@ -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] @@ -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]]] = {} diff --git a/miles/backends/fsdp_utils/loss_hub/__init__.py b/miles/backends/fsdp_utils/loss_hub/__init__.py index 651570b37..1c54d3176 100644 --- a/miles/backends/fsdp_utils/loss_hub/__init__.py +++ b/miles/backends/fsdp_utils/loss_hub/__init__.py @@ -19,8 +19,10 @@ ) from miles.backends.fsdp_utils.loss_hub.flow_grpo import flow_grpo_loss_formula, prepare_flow_grpo_batch from miles.backends.fsdp_utils.loss_hub.nft import nft_loss_formula, prepare_nft_batch +from miles.backends.fsdp_utils.loss_hub.pdd import pdd_loss_formula, prepare_pdd_batch from miles.backends.fsdp_utils.loss_hub.sft import prepare_sft_batch, sft_loss_formula from miles.backends.fsdp_utils.loss_hub.types import DiffusionLossContext, PreparedBatch +from miles.distillation.integration import expand_train_pairs from miles.utils.misc import load_function __all__ = ["LOSS_HOOKS", "DiffusionLossContext", "LossHooks", "PreparedBatch", "get_loss_hooks"] @@ -50,6 +52,7 @@ class LossHooks: ("sft_loss", "actor"): LossHooks(prepare_sft_batch, sft_loss_formula), ("dmd2", "actor"): LossHooks(prepare_generator_batch, dmd2_loss_formula, train_input=select_scored_pairs), ("dmd2", "critic"): LossHooks(prepare_critic_batch, critic_loss_formula, train_output=score_last_step_samples), + ("pdd", "actor"): LossHooks(prepare_pdd_batch, pdd_loss_formula, train_input=expand_train_pairs), } diff --git a/miles/backends/fsdp_utils/loss_hub/pdd.py b/miles/backends/fsdp_utils/loss_hub/pdd.py new file mode 100644 index 000000000..cbd8688be --- /dev/null +++ b/miles/backends/fsdp_utils/loss_hub/pdd.py @@ -0,0 +1,111 @@ +"""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. +""" + +import torch + +from miles.distillation.integration import model_time, pdd_grid +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 + 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) + 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(): + 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. + condition = { + k: ( + (v.to(ctx.device).float() if v.is_floating_point() else v.to(ctx.device)) + if isinstance(v, torch.Tensor) + else v + ) + for k, v in condition.items() + } + + def solve(forward): + def teacher(x, sigma): + return forward({STREAM: x}, {STREAM: sigma.reshape(1)})[STREAM].float() + + target = teacher_mean_velocity(teacher, x_selected, grid[selected], grid.diff()[selected], solver="midpoint") + return {STREAM: target} + + 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)}, + model=ctx.models["transformer"], + component_name="transformer", + guidance_scale=1.0, + use_cfg=False, + cfg_batching=False, + true_cfg_scale=1.0, + pos_cond=condition, + neg_cond=None, + joint_cond=None, + advantage=torch.ones(1, device=ctx.device), + extras={"start": start, "selected": selected, "lane": lane, "grid": grid}, + teacher_guidance_scale=1.0, + teacher_solver=solve, + ) + + +def pdd_loss_formula( + ctx, + batch, + prepared, + *, + new_pred, + old_pred, + ref_pred, + teacher_pred=None, + metrics, + optim_step_idx, + train_output_inputs, + write_old_log_prob=False, + old_log_prob_from_new=False, +): + if old_pred is not None or ref_pred is not None or write_old_log_prob or old_log_prob_from_new: + raise ValueError("PDD does not consume policy/reference predictions") + 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")) + 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") + 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/loss_hub/types.py b/miles/backends/fsdp_utils/loss_hub/types.py index 449d49a34..9abd47ec6 100644 --- a/miles/backends/fsdp_utils/loss_hub/types.py +++ b/miles/backends/fsdp_utils/loss_hub/types.py @@ -3,6 +3,7 @@ from __future__ import annotations from argparse import Namespace +from collections.abc import Callable from dataclasses import dataclass, field from typing import Any @@ -71,3 +72,7 @@ class PreparedBatch: extras: dict[str, Any] = field(default_factory=dict) # CFG scale of the frozen teacher's no-grad forward on this batch; None runs no teacher forward. teacher_guidance_scale: float | None = None + # With a teacher scale set: ``solver(forward)`` replaces the single teacher forward on this batch's inputs. + # ``forward(latents, timesteps_for_model)`` runs the frozen teacher, owned by the actor, on other latent + # states with this batch's conditioning; the solver's return value reaches the formula as ``teacher_pred``. + teacher_solver: Callable[[Callable[[dict, dict], dict]], Any] | None = None diff --git a/miles/backends/fsdp_utils/lr_scheduler.py b/miles/backends/fsdp_utils/lr_scheduler.py index 9bbe1efd1..d1d5eca71 100644 --- a/miles/backends/fsdp_utils/lr_scheduler.py +++ b/miles/backends/fsdp_utils/lr_scheduler.py @@ -167,7 +167,7 @@ def get_lr_scheduler(args, optimizer: torch.optim.Optimizer) -> FSDPLRScheduler: Returns: FSDPLRScheduler: Initialized scheduler bound to ``optimizer``. """ - args.train_iters = args.num_rollout * args.rollout_batch_size * args.n_samples_per_prompt // args.global_batch_size + args.train_iters = args.num_rollout * args.num_steps_per_rollout if args.lr_decay_iters is None: args.lr_decay_iters = args.train_iters lr_decay_steps = args.lr_decay_iters diff --git a/miles/backends/fsdp_utils/metrics.py b/miles/backends/fsdp_utils/metrics.py index 7b7317801..277e28d87 100644 --- a/miles/backends/fsdp_utils/metrics.py +++ b/miles/backends/fsdp_utils/metrics.py @@ -46,6 +46,8 @@ "x0_rel_max": MetricReduce.MAX, "peak_memory_allocated_gb": MetricReduce.MAX, "device_memory_used_gb": MetricReduce.MAX, + "pdd_next_latent_mae": MetricReduce.MEAN, + "pdd_update_relative_error": 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/fsdp_utils/model_loader.py b/miles/backends/fsdp_utils/model_loader.py index ca61e39ec..da30a5722 100644 --- a/miles/backends/fsdp_utils/model_loader.py +++ b/miles/backends/fsdp_utils/model_loader.py @@ -29,6 +29,11 @@ def load_fsdp_models( ) -> dict[str, torch.nn.Module]: materialize_weights = dist.get_rank() == 0 master_dtype = parse_dtype_from_str(args.fsdp_master_dtype) + transform_model = None + if trainable and args.custom_train_model_transform_path is not None: + from miles.utils.misc import load_function + + transform_model = load_function(args.custom_train_model_transform_path) models = {} for component_index, component in enumerate(args.update_weight_target_modules): with model_init_context(materialize_weights=materialize_weights): @@ -46,6 +51,9 @@ def load_fsdp_models( model = load_lora_adapter(model, lora_adapter_paths[component_index], trainable=trainable) elif trainable and args.use_lora: model = apply_lora(model, args, train_pipeline_config) + if transform_model is not None: + # After LoRA, so the parameters it adds train in full beside the adapters. + transform_model(model.get_base_model() if hasattr(model, "get_base_model") else model, args) model.train(trainable) if not trainable: model.requires_grad_(False) @@ -162,7 +170,7 @@ def apply_fsdp2( modules = [module for name, module in model.named_modules() if module.__class__.__name__ in layer_cls_to_wrap] - param_dtype = parse_dtype_from_str(args.diffusion_forward_dtype) + param_dtype = parse_dtype_from_str(args.fsdp_param_dtype or args.diffusion_forward_dtype) reduce_dtype = parse_dtype_from_str(args.fsdp_reduce_dtype) # A wrap entry may also be a module LIST — fully_shard can group several modules into one wrap # (one shared all-gather); today every wrap holds a single block. diff --git a/miles/backends/sglang_diffusion_utils/monkey_patches/__init__.py b/miles/backends/sglang_diffusion_utils/monkey_patches/__init__.py index 7df770a8b..2ac94191e 100644 --- a/miles/backends/sglang_diffusion_utils/monkey_patches/__init__.py +++ b/miles/backends/sglang_diffusion_utils/monkey_patches/__init__.py @@ -9,6 +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``). Patch modules are imported inside ``apply_*`` only, so CPU-only Ray actors can import this package without pulling sglang triton kernels. Adding a @@ -57,6 +58,13 @@ def apply_wan_rollout_patches() -> None: patch_wan_norm_ops.apply() +@register_rollout_patch_group("pdd_qwen_image21") +def apply_pdd_qwen_image21_rollout_patches() -> None: + from . import patch_pdd_qwen_image21 + + patch_pdd_qwen_image21.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_qwen_image21.py b/miles/backends/sglang_diffusion_utils/monkey_patches/patch_pdd_qwen_image21.py new file mode 100644 index 000000000..498b40abe --- /dev/null +++ b/miles/backends/sglang_diffusion_utils/monkey_patches/patch_pdd_qwen_image21.py @@ -0,0 +1,125 @@ +"""PDD rollout for Qwen-Image 2.1: keep the native DiT and rollout scheduler, replace only ``proj_out``. + +The ODE scheduler steps all 32 intervals. The first interval of each block runs the +DiT, whose 32 heads are cached; the block's other three intervals step on the cached +heads without a forward. The native trajectory capture thus returns every interval's +start state (33 states, 8 forwards), which the trainer's teacher target starts from. +No fused-head cache or exported checkpoint is needed for online weight sync. +""" + +import torch +from torch import nn + +from miles.distillation.integration import ( + BLOCK_SIZE, + IMAGE_TOKENS, + NUM_INTERVALS, + RESOLUTION, + engine_timesteps, + make_grid, +) +from miles.distillation.pdd import ParallelLinear + + +class PDDProjection(nn.Module): + def __init__(self, source): + super().__init__() + self.parallel = ParallelLinear(source, NUM_INTERVALS) + self.interval = None + self.block = None + + def forward(self, hidden): + # One forward per block; FP32 head outputs, even under BF16 autocast. + self.block = self.parallel(hidden).float() + return self.block[0] + + +def apply(): + from sglang.multimodal_gen.configs.pipeline_configs.qwen_image21 import QwenImage21PipelineConfig + from sglang.multimodal_gen.runtime.models.dits.qwen_image21 import QwenImage21Transformer2DModel + from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.qwen_image21 import ( + QwenImage21DenoisingStage, + ) + from sglang.multimodal_gen.runtime.pipelines_core.stages.timestep_preparation import TimestepPreparationStage + + if getattr(QwenImage21DenoisingStage, "_miles_pdd", False): + return + original_load = QwenImage21Transformer2DModel.post_load_weights + original_time = TimestepPreparationStage.forward + original_prepare = QwenImage21DenoisingStage._prepare_denoising_loop + original_step = QwenImage21DenoisingStage._run_denoising_step + original_predict = QwenImage21DenoisingStage._predict_noise + + # Request and engine-size settings are validated by Miles' PDD arguments; the + # checks here cover the patch's own constants and server-only options. + def post_load(self): + original_load(self) + if not isinstance(self.proj_out, PDDProjection): + self.proj_out = PDDProjection(self.proj_out) + + def timesteps(self, batch, server_args): + if not isinstance(server_args.pipeline_config, QwenImage21PipelineConfig): + return original_time(self, batch, server_args) + if (batch.height, batch.width, batch.num_inference_steps) != ( + RESOLUTION, + RESOLUTION, + NUM_INTERVALS // BLOCK_SIZE, + ): + raise ValueError(f"PDD requires {RESOLUTION}x{RESOLUTION} and {NUM_INTERVALS // BLOCK_SIZE} steps") + batch = original_time(self, batch, server_args) + grid = make_grid(server_args.model_path, NUM_INTERVALS, IMAGE_TOKENS, batch.timesteps.device) + # Every interval is a scheduler step; only block starts reach the DiT, at these timesteps. + batch.timesteps = engine_timesteps(grid[:-1]).to(grid.device) + batch.scheduler.timesteps = batch.timesteps + batch.scheduler.sigmas = grid + batch.num_inference_steps = NUM_INTERVALS + return batch + + def prepare(self, batch, server_args): + if server_args.enable_torch_compile or server_args.enable_breakable_cuda_graph or server_args.cache_dit_config: + raise ValueError("PDD graph/Cache-DiT modes are not validated") + if server_args.dit_layerwise_offload or server_args.use_fsdp_inference: + raise ValueError("PDD requires a resident native transformer") + if len(batch.extra["qwen21_positive"]["layouts"]) != 1: + raise ValueError("PDD requires batch size 1") + if batch.extra["qwen21_positive"].get("condition_latents") is not None: + raise ValueError("PDD does not support image conditioning") + batch.latents = batch.latents.bfloat16().float() + ctx = original_prepare(self, batch, server_args) + if not isinstance(self.transformer.proj_out, PDDProjection): + raise ValueError("PDD output heads were not installed") + return ctx + + def predict(self, current_model, *args, **kwargs): + head = current_model.proj_out + if head.interval % BLOCK_SIZE == 0: + original_predict(self, current_model, *args, **kwargs) + return head.block[head.interval] + + def step(self, ctx, step, batch, server_args): + step.current_model.proj_out.interval = step.step_index + with torch.autocast(ctx.latents.device.type, dtype=torch.bfloat16): + original_step(self, ctx, step, batch, server_args) + if not torch.isfinite(ctx.latents).all(): + raise FloatingPointError("Nonfinite PDD rollout") + + # Reuse the existing train/rollout prefix-cache policy, without replacing + # the transformer forward, time embeddings, normalization, or RoPE. + from .patch_qwen_image21 import apply as apply_qwen_image21 + + apply_qwen_image21() + # Native fast paths are bit-exact only against the engine's BF16-weight path; + # with FP32 weights some reject the dtype (Q/K norm + RoPE). Use the eager path. + from sglang.kernels.ops.diffusion.sites.bitexact_gate import BitExactFusionGate + from sglang.multimodal_gen.runtime.models.dits import qwen_image21 as native + + for gate in vars(native).values(): + if isinstance(gate, BitExactFusionGate): + gate.disable() + QwenImage21Transformer2DModel.post_load_weights = post_load + TimestepPreparationStage.forward = timesteps + QwenImage21PipelineConfig.supports_dynamic_batching = lambda self: False + QwenImage21DenoisingStage._prepare_denoising_loop = prepare + QwenImage21DenoisingStage._run_denoising_step = step + QwenImage21DenoisingStage._predict_noise = predict + QwenImage21DenoisingStage._miles_pdd = True diff --git a/miles/backends/training_utils/weight_update/hf_weight_iterator/__init__.py b/miles/backends/training_utils/weight_update/hf_weight_iterator/__init__.py index d2a0a8658..b0d137af2 100644 --- a/miles/backends/training_utils/weight_update/hf_weight_iterator/__init__.py +++ b/miles/backends/training_utils/weight_update/hf_weight_iterator/__init__.py @@ -39,6 +39,18 @@ def iter_hf_adapter_weights(self) -> Iterator[list[tuple[str, torch.Tensor]]]: ) yield from pack_units_by_size(hf_adapter_units, self.args.update_weight_buffer_size) + def iter_hf_trained_weights(self) -> Iterator[list[tuple[str, torch.Tensor]]]: + """Parameters trained in full beside a LoRA adapter (e.g. a layer the model-transform hook added), + bucketed like ``iter_hf_weights``; a LoRA sync pushes them as plain weights after the adapter.""" + hf_trained_units = assemble_atomic_update_groups( + self._iter_hf_trained_units(), self._hf_atomic_update_groups() + ) + yield from pack_units_by_size(hf_trained_units, self.args.update_weight_buffer_size) + + def _iter_hf_trained_units(self) -> Iterator[list[tuple[str, torch.Tensor]]]: + """Backend hook: units of the parameters trained in full beside a LoRA adapter. Default none.""" + return iter(()) + @abstractmethod def _iter_hf_param_units(self) -> Iterator[list[tuple[str, torch.Tensor]]]: """Backend hook: one unit per training-side parameter, holding every HF diff --git a/miles/distillation/__init__.py b/miles/distillation/__init__.py new file mode 100644 index 000000000..965a111cd --- /dev/null +++ b/miles/distillation/__init__.py @@ -0,0 +1 @@ +"""Experimental diffusion distillation primitives, independent of Ray and rollout engines.""" diff --git a/miles/distillation/integration.py b/miles/distillation/integration.py new file mode 100644 index 000000000..7a32f05f7 --- /dev/null +++ b/miles/distillation/integration.py @@ -0,0 +1,203 @@ +"""PDD protocol shared by the Miles actor, loader and the SGLang rollout patches. + +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``. +""" + +import functools + +import torch + +from .pdd import ParallelLinear, validate_grid + + +def make_grid(model_path, intervals, tokens, device="cpu"): + return _cached_grid(str(model_path), intervals, tokens).to(device, copy=True) + + +@functools.lru_cache(maxsize=8) +def _cached_grid(model_path, intervals, tokens): + import numpy as np + from diffusers import FlowMatchEulerDiscreteScheduler + from diffusers.pipelines.qwenimage21.pipeline_qwenimage21 import calculate_shift + + scheduler = FlowMatchEulerDiscreteScheduler.from_pretrained( + model_path, subfolder="scheduler", local_files_only=True + ) + cfg = scheduler.config + mu = calculate_shift(tokens, cfg.base_image_seq_len, cfg.max_image_seq_len, cfg.base_shift, cfg.max_shift) + scheduler.set_timesteps(intervals, sigmas=np.linspace(1.0, 1.0 / intervals, intervals), mu=mu) + grid = scheduler.sigmas.float() + validate_grid(grid) + return grid + + +def engine_timesteps(sigmas): + """SGLang timesteps whose BF16 time-embedding input equals the trainer's. + + Under BF16 autocast the native DiT embeds ``bf16(bf16(t) / 1000)``, while the + Diffusers trainer embeds ``bf16(sigma)``; ``t = 1000 * sigma`` can round to a + different value. Pick the representable ``t`` nearest ``1000 * sigma`` that + lands on the trainer's value, or the nearest reachable value when none does; + the online trainer then feeds ``embedded_sigmas`` of that choice. + """ + result = [] + for sigma in sigmas.detach().float().cpu(): + target = float(sigma.bfloat16()) + center = float(sigma) * 1000 + candidates = torch.arange(center - 16, center + 16, 1 / 16).bfloat16().unique().float() + miss = ((candidates.bfloat16() / 1000).float() - target).abs() + # Lexicographic: embedding mismatch first, then distance from 1000 * sigma. + best = torch.argmin(miss * 1e6 + (candidates - center).abs()) + result.append(candidates[best]) + return torch.stack(result) + + +def embedded_sigmas(timesteps): + """The sigma the native SGLang DiT embeds for ``timesteps`` under BF16 autocast.""" + return (timesteps.bfloat16() / 1000).float() + + +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.""" + + def __init__(self, source, num_intervals): + super().__init__() + self.parallel = ParallelLinear(source, num_intervals) + + 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). +NUM_INTERVALS, BLOCK_SIZE = 32, 4 +RESOLUTION = 1024 +IMAGE_TOKENS = (RESOLUTION // 16) ** 2 +PATCH_GROUP = "pdd_qwen_image21" + + +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) + + +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 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) + + +def expand_trajectories(pairs, *, intervals, block_size): + """Called AFTER DP splitting; each local window keeps the same ordered prompts.""" + if len({p["sample_index"] for p in pairs}) != len(pairs): + raise ValueError("PDD needs a distinct lane ID per sampled prompt occurrence") + return [dict(pair, pdd_start=start) for start in range(0, intervals, block_size) for pair in pairs] + + +def expand_train_pairs(ctx, train_pairs): + """PDD's train-input hook: one block-ordered update per trajectory block.""" + return expand_trajectories(train_pairs, intervals=ctx.args.pdd_num_intervals, block_size=ctx.args.pdd_block_size) + + +_HOOK_DEFAULTS = { + "custom_convert_samples_to_train_data_path": "miles.rollout.pdd_rollout.convert_samples_to_train_data", + "custom_rm_path": "miles.rollout.pdd_rollout.no_reward", + "custom_train_model_transform_path": "miles.distillation.integration.install_student", +} +_DIFFUSION_ROLLOUT = "miles.rollout.sglang_diffusion_rollout.generate_rollout" + + +def set_pdd_defaults(args): + """Fill PDD's rollout/loader hooks and schedule (the loss hub supplies its train hooks); + ``validate_pdd_args`` rejects explicit conflicting values.""" + for key, value in _HOOK_DEFAULTS.items(): + if getattr(args, key) is None: + 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" + if args.teacher_load is None: + args.teacher_load = args.hf_checkpoint + args.rollout_return_full_trajectory = True + # One optimizer update per block; each update sees every trajectory lane once. + if args.num_steps_per_rollout is None: + args.num_steps_per_rollout = args.pdd_num_intervals // args.pdd_block_size + if args.global_batch_size is None: + args.global_batch_size = args.rollout_batch_size + + +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}") + 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"]: + raise ValueError("PDD trains only the transformer component") + if (args.pdd_num_intervals, args.pdd_block_size) != (NUM_INTERVALS, BLOCK_SIZE): + raise ValueError("PDD uses 32 intervals and block size 4 (8 student forwards)") + if args.micro_batch_size != 1 or args.micro_batch_size_sample is not None: + raise ValueError("PDD requires --micro-batch-size 1 and no legacy sample/timestep tiling") + if args.sequence_parallel_size != 1: + raise ValueError("PDD sequence parallelism is not yet validated; use FSDP with SP=1") + # The student is LoRA on the backbone plus its new heads, trained in full; the teacher is the frozen base. + if not args.use_lora: + raise ValueError("PDD trains a LoRA student (plus full heads); pass --use-lora") + # The engine applies the adapter unmerged like the trainer: merged BF16 weights would round most of the + # adapter's update away. The heads go as plain weights after the adapter. + if args.colocate and not args.lora_ipc_weight_sync: + raise ValueError("PDD syncs the LoRA adapter itself; pass --lora-ipc-weight-sync") + if getattr(args, "sglang_lora_merge_mode", None) != "dynamic": + raise ValueError("PDD needs the engine's unmerged LoRA forward; pass --sglang-lora-merge-mode dynamic") + if args.use_ema or args.ref_load or args.ref_mode != "none": + raise ValueError("PDD uses a frozen teacher; no EMA or reference model") + if args.teacher_lora_adapter_paths or args.lora_adapter_paths: + raise ValueError("PDD starts the student from the base model; no initial or teacher LoRA adapters") + if args.diffusion_recompute_old_log_prob or args.diffusion_kl_beta: + raise ValueError("PDD does not use RL log probabilities or KL") + if args.diffusion_guidance_scale != 1 or args.diffusion_true_cfg_scale not in (None, 1): + raise ValueError("PDD requires CFG=1") + if not args.prompt_data or not args.rollout_global_dataset: + raise ValueError("PDD requires --prompt-data and the global dataset") + if args.n_samples_per_prompt != 1: + raise ValueError("PDD requires --n-samples-per-prompt 1") + if args.fsdp_master_dtype != "fp32" or args.diffusion_forward_dtype != "bf16": + raise ValueError("PDD uses FP32 master weights and BF16 forward") + if args.teacher_load != args.hf_checkpoint: + raise ValueError("PDD teacher must be the same base model as --hf-checkpoint") + # Rollout engine: the full 8-step ODE trajectory, unguided, one sample per request. + if args.diffusion_num_steps != 8 or args.diffusion_eval_num_steps not in (None, 8): + raise ValueError("PDD requires 8 training/evaluation steps") + if args.diffusion_sde_type != "ode" or args.diffusion_noise_level != 0: + 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.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") + for key, value in {**_HOOK_DEFAULTS, "rollout_function_path": _DIFFUSION_ROLLOUT}.items(): + if getattr(args, key) != value: + raise ValueError(f"PDD requires {key}={value}") + if args.num_steps_per_rollout != args.pdd_num_intervals // args.pdd_block_size: + raise ValueError("PDD performs one optimizer update per block (8 per rollout)") + if args.global_batch_size != args.rollout_batch_size: + raise ValueError("PDD global batch size equals the number of trajectory lanes (rollout batch size)") diff --git a/miles/distillation/pdd.py b/miles/distillation/pdd.py new file mode 100644 index 000000000..ba0eb02b6 --- /dev/null +++ b/miles/distillation/pdd.py @@ -0,0 +1,78 @@ +"""Parallel Decoding Distillation (arXiv:2607.26004, equations 9--15). + +The grid may increase (paper time) or decrease (diffusers sigma). The teacher +must return derivatives with respect to that same coordinate. Predictions use +shape [interval, batch, ...]; interval indices are absolute, not block-relative. +""" + +from __future__ import annotations + +from collections.abc import Callable + +import torch +from torch import nn + + +def validate_grid(grid: torch.Tensor) -> None: + if grid.ndim != 1 or grid.numel() < 2 or not torch.isfinite(grid).all(): + raise ValueError("grid must be a finite 1D tensor with at least two points") + delta = grid.diff() + if not ((delta > 0).all() or (delta < 0).all()): + raise ValueError("grid must be strictly monotonic") + + +class ParallelLinear(nn.Module): + """N independent output projections initialized from one pretrained layer.""" + + def __init__(self, source: nn.Linear, num_intervals: int): + super().__init__() + if num_intervals < 1: + raise ValueError("num_intervals must be positive") + self.weight = nn.Parameter(source.weight.detach().unsqueeze(0).repeat(num_intervals, 1, 1)) + self.bias = ( + nn.Parameter(source.bias.detach().unsqueeze(0).repeat(num_intervals, 1)) + if source.bias is not None + else None + ) + + def forward(self, hidden: torch.Tensor) -> torch.Tensor: + result = torch.einsum("...i,koi->k...o", hidden, self.weight) + if self.bias is not None: + result = result + self.bias.reshape(self.bias.shape[0], *([1] * (hidden.ndim - 1)), -1) + return result + + +@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.""" + 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: + raise ValueError("teacher output must match the latent shape exactly") + return velocity + + x = x.detach() + velocity = call(x, time) + if solver == "midpoint": + velocity = call(x + 0.5 * delta * velocity, time + 0.5 * delta) + return velocity.detach() + + +def block_update(x: torch.Tensor, predictions: torch.Tensor, grid: torch.Tensor, start: int, end: int) -> torch.Tensor: + """Accumulate signed interval lengths in fp32 (or fp64 for fp64 inputs).""" + if predictions.shape != (len(grid) - 1, *x.shape): + raise ValueError("predictions must have shape [num_intervals, *latent.shape]") + if not 0 <= start <= end < len(grid): + raise ValueError("invalid block bounds") + dtype = torch.float64 if x.dtype == torch.float64 else torch.float32 + h = grid.diff()[start:end].to(device=x.device, dtype=dtype) + return x.to(dtype) + torch.einsum("k,k...->...", h, predictions[start:end].to(dtype)) + + +def interval_loss(predictions: torch.Tensor, selected: int, target: torch.Tensor) -> torch.Tensor: + """Per-sample squared error of the selected head against the teacher's mean velocity.""" + error = (predictions[selected].float() - target.float()).square() + return error.flatten(1).mean(1) diff --git a/miles/rollout/pdd_rollout.py b/miles/rollout/pdd_rollout.py new file mode 100644 index 000000000..9bdd4e018 --- /dev/null +++ b/miles/rollout/pdd_rollout.py @@ -0,0 +1,45 @@ +"""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 +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 +parser, dataset cursor and weight sync. +""" + +import torch + +from miles.distillation.integration import pdd_grid + + +async def no_reward(args, samples, **kwargs): + # PDD has a teacher loss, no reward model. The shared rollout logger expects + # a numeric reward; this placeholder must not be interpreted as image quality. + return [0.0] * len(samples) + + +def convert_samples_to_train_data(args, samples): + grid = pdd_grid(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): + 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. + if traj.latents is None or traj.latents.shape[0] != states_count: + raise ValueError(f"PDD requires the full {states_count}-state interval trajectory") + if traj.latent_step_indices is not None and traj.latent_step_indices.tolist() != list(range(states_count)): + raise ValueError(f"PDD trajectory indices must be 0..{states_count - 1}") + states = traj.latents.detach().cpu().float() + if states.ndim != 3: + 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)) + if not pairs: + raise ValueError("PDD rollout produced no training samples") + return {"train_data": pairs} diff --git a/miles/utils/arguments.py b/miles/utils/arguments.py index d943d311c..15efe6bd2 100644 --- a/miles/utils/arguments.py +++ b/miles/utils/arguments.py @@ -162,6 +162,17 @@ def add_train_arguments(parser): "--diffusion-forward-dtype." ), ) + parser.add_argument( + "--fsdp-param-dtype", + type=str, + default=None, + choices=["fp16", "bf16", "fp32"], + help=( + "dtype FSDP all-gathers parameters to (MixedPrecisionPolicy.param_dtype). Defaults to " + "--diffusion-forward-dtype; fp32 keeps gathered weights (biases, norms) at master " + "precision and leaves matmul precision to autocast." + ), + ) parser.add_argument( "--fsdp-reduce-dtype", type=str, @@ -949,7 +960,7 @@ def add_algo_arguments(parser): parser.add_argument( "--loss-type", type=str, - choices=["policy_loss", "sft_loss", "custom_loss", "nft", "dmd2"], + choices=["policy_loss", "sft_loss", "custom_loss", "nft", "dmd2", "pdd"], default="policy_loss", help=( "Train objective. Each loss type selects its prepare / loss-formula / train-input / train-output " @@ -959,6 +970,8 @@ def add_algo_arguments(parser): "DiT forward always stays in the FSDP actor." ), ) + parser.add_argument("--pdd-num-intervals", type=int, default=32) + parser.add_argument("--pdd-block-size", type=int, default=4) parser.add_argument( "--custom-prepare-train-batch-path", type=str, @@ -969,6 +982,17 @@ def add_algo_arguments(parser): "Builds DiT inputs; --loss-type custom_loss only, default is Flow-GRPO SDE-pair stacking." ), ) + parser.add_argument( + "--custom-train-model-transform-path", + type=str, + default=None, + help=( + "Dotted path to `fn(model, args) -> None` that edits each trainable component in place " + "after loading and LoRA, before FSDP wrapping (e.g. replacing an output layer). Parameters it " + "adds train in full beside any LoRA adapters and are kept in LoRA checkpoints. Runs on " + "meta-initialized modules on non-zero ranks." + ), + ) parser.add_argument( "--custom-loss-function-path", type=str, @@ -1841,6 +1865,11 @@ def set_default_diffusion_args(args) -> None: if args.critic_lr is None: args.critic_lr = args.lr + if args.loss_type == "pdd": + from miles.distillation.integration import set_pdd_defaults + + set_pdd_defaults(args) + if args.ref_mode is None: args.ref_mode = "lora_base" if args.diffusion_kl_beta > 0 else "none" @@ -2150,6 +2179,10 @@ def miles_validate_args(args): f"{cfg_cls.__name__} trains --diffusion-task {list(cfg_cls.tasks)}, got {args.diffusion_task!r}" ) cfg_cls.validate_args(args) + if args.loss_type == "pdd": + from miles.distillation.integration import validate_pdd_args + + validate_pdd_args(args) if args.use_lora and args.lora_target_modules is None: args.lora_target_modules = list(cfg_cls.lora_target_modules) @@ -2375,13 +2408,18 @@ def miles_validate_args(args): if args.num_steps_per_rollout is not None: samples_per_rollout = args.rollout_batch_size * args.n_samples_per_prompt derived_gbs = samples_per_rollout // args.num_steps_per_rollout - if args.global_batch_size is not None and args.global_batch_size != derived_gbs: + from miles.backends.fsdp_utils.loss_hub import get_loss_hooks + + # A train-input hook may expand or select pairs, so it defines how many samples each optimizer step + # sees; an explicit global batch size then stands. + if args.global_batch_size is None: + args.global_batch_size = derived_gbs + elif args.global_batch_size != derived_gbs and get_loss_hooks(args, "actor").train_input is None: raise ValueError( f"global_batch_size={args.global_batch_size} contradicts " f"rollout_batch_size×n_samples_per_prompt÷num_steps_per_rollout={derived_gbs}; " f"do not pass both." ) - args.global_batch_size = derived_gbs train_world_size = args.actor_num_gpus_per_node * args.actor_num_nodes dp_size = train_world_size // args.sequence_parallel_size diff --git a/tests/fast-gpu/backends/fsdp_utils/_param_dtype_map_integration_worker.py b/tests/fast-gpu/backends/fsdp_utils/_param_dtype_map_integration_worker.py index d38637233..57ca17ae8 100644 --- a/tests/fast-gpu/backends/fsdp_utils/_param_dtype_map_integration_worker.py +++ b/tests/fast-gpu/backends/fsdp_utils/_param_dtype_map_integration_worker.py @@ -96,6 +96,7 @@ def main(): ), args=Namespace( diffusion_forward_dtype="bf16", + fsdp_param_dtype=None, fsdp_reduce_dtype="fp32", gradient_checkpointing=False, ), 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 new file mode 100644 index 000000000..6fc953c9a --- /dev/null +++ b/tests/fast-gpu/backends/sglang_diffusion_utils/test_pdd_sglang_loop.py @@ -0,0 +1,285 @@ +"""Native SGLang stage -> PDD updates on FSDP -> weight sync -> native stage. + +Random tiny weights and synthetic embeddings, no pretrained download. The worker +subprocess isolates SGLang globals/patches from other tests in this suite. +""" + +import os +import subprocess +import sys +from pathlib import Path +from types import SimpleNamespace + +import pytest +import torch +from tests.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=60, suite="stage-b-5-gpu-h200", labels=["fsdp"]) + + +@pytest.mark.skipif(not torch.cuda.is_available(), reason="Requires CUDA/SGLang") +def test_online_stage_train_sync(tmp_path): + subprocess.run( + [sys.executable, __file__, "--worker", str(tmp_path)], + check=True, + timeout=180, + env={**os.environ, "PYTHONPATH": "."}, + ) + + +def worker(output): + import dataclasses + import socket + + from diffusers import FlowMatchEulerDiscreteScheduler as HFScheduler + from diffusers import QwenImage21Transformer2DModel as HFModel + from peft import LoraConfig, get_peft_model + from sglang.multimodal_gen.configs.models.dits.qwenimage21 import QwenImage21ArchConfig, QwenImage21DitConfig + from sglang.multimodal_gen.configs.pipeline_configs.qwen_image21 import QwenImage21PipelineConfig + from sglang.multimodal_gen.runtime.distributed.parallel_state import ( + maybe_init_distributed_environment_and_model_parallel, + ) + from sglang.multimodal_gen.runtime.managers.memory_managers.component_manager import ComponentResidencyManager + from sglang.multimodal_gen.runtime.models.dits.qwen_image21 import QwenImage21Transformer2DModel as Native + from sglang.multimodal_gen.runtime.models.dits.qwen_image21 import build_layout + from sglang.multimodal_gen.runtime.models.schedulers.scheduling_flow_match_euler_discrete import ( + FlowMatchEulerDiscreteScheduler, + ) + from sglang.multimodal_gen.runtime.pipelines_core.schedule_batch import Req + from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.qwen_image21 import ( + QwenImage21DenoisingStage, + prepare_qwen21_mu, + ) + from sglang.multimodal_gen.runtime.pipelines_core.stages.timestep_preparation import TimestepPreparationStage + from sglang.multimodal_gen.runtime.post_training.weights_updater import WeightsUpdater + from sglang.multimodal_gen.runtime.server_args import ServerArgs, set_global_server_args + from torch.distributed.device_mesh import init_device_mesh + from torch.distributed.fsdp import MixedPrecisionPolicy, fully_shard + + from miles.backends.fsdp_utils.configs.qwen_image21 import QwenImage21TrainPipelineConfig + from miles.backends.fsdp_utils.hf_weight_iterator import FSDPHfWeightIterator + from miles.backends.fsdp_utils.loss_hub.pdd import pdd_loss_formula, prepare_pdd_batch + from miles.backends.fsdp_utils.loss_hub.types import DiffusionLossContext + from miles.backends.fsdp_utils.metrics import SCHEMA + from miles.backends.sglang_diffusion_utils.monkey_patches import patch_pdd_qwen_image21 + from miles.distillation.integration import expand_train_pairs, install_student + from miles.distillation.pdd import block_update + from miles.rollout.pdd_rollout import convert_samples_to_train_data + from miles.utils.diffusion_rollout_response import _parse_denoising_env, _parse_dit_trajectory + from miles.utils.types import Sample + + torch.cuda.set_device(0) + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + port = sock.getsockname()[1] + os.environ.update(MASTER_ADDR="127.0.0.1", MASTER_PORT=str(port), RANK="0", LOCAL_RANK="0", WORLD_SIZE="1") + # The real head width: native Q/K norm + RoPE fast paths only fire at 128. + cfg = dict( + in_channels=4, + out_channels=4, + num_layers=1, + num_attention_heads=1, + attention_head_dim=128, + context_in_dim=16, + mlp_ratio=2, + axes_dims_rope=(16, 56, 56), + ) + model_path = output / "model" + HFScheduler(use_dynamic_shifting=True).save_pretrained(model_path / "scheduler") + config = QwenImage21DitConfig(arch_config=QwenImage21ArchConfig(**cfg)) + server = ServerArgs( + model_path=str(model_path), + num_gpus=1, + attention_backend="torch_sdpa", + pipeline_config=QwenImage21PipelineConfig(dit_config=config, dit_precision="fp32"), + ) + set_global_server_args(server) + maybe_init_distributed_environment_and_model_parallel(tp_size=1, sp_size=1) + patch_pdd_qwen_image21.apply() + patch_pdd_qwen_image21.apply() # idempotent in scheduler workers + + # Trainer: FSDP LoRA student with 32 full heads and a frozen FP32-master teacher, both under BF16 autocast. + torch.manual_seed(72) + student = HFModel(**cfg).cuda() + teacher = HFModel(**cfg).cuda().eval().requires_grad_(False) + args = SimpleNamespace( + diffusion_model_family="qwen_image21", + pdd_num_intervals=32, + pdd_block_size=4, + hf_checkpoint=str(model_path), + diffusion_height=1024, + diffusion_width=1024, + seed=42, + update_weight_buffer_size=4096, + ) + # The loader's order: LoRA on the backbone, then the heads (trained in full) on the unwrapped model. + student = get_peft_model( + student, LoraConfig(r=4, lora_alpha=8, target_modules=QwenImage21TrainPipelineConfig.lora_target_modules) + ) + install_student(student.get_base_model(), args) + train_config = QwenImage21TrainPipelineConfig() + train_config.configure(args) + for model in (student, teacher): + train_config.postprocess_model_after_materialize(model) + fp32 = MixedPrecisionPolicy(param_dtype=torch.float32, reduce_dtype=torch.float32, cast_forward_inputs=False) + fully_shard(student, mesh=init_device_mesh("cuda", (1,)), mp_policy=fp32) + trained = [p for p in student.parameters() if p.requires_grad] + optimizer = torch.optim.AdamW(trained, lr=1e-3, weight_decay=0, foreach=False) + + # Engine: native transformer and stages, patched for PDD. + native = Native(config, {}).cuda().eval() + native.post_load_weights() + scheduler = FlowMatchEulerDiscreteScheduler.from_pretrained(model_path / "scheduler") + time_stage = TimestepPreparationStage(scheduler, [prepare_qwen21_mu]) + stage = QwenImage21DenoisingStage(transformer=native, scheduler=scheduler) + pipeline = SimpleNamespace( + modules={"transformer": native}, component_residency_strategies={}, _stage_name_mapping={"denoising": stage} + ) + manager = ComponentResidencyManager(pipeline, server) + manager.refresh_pipeline(pipeline) + stage.set_component_residency_manager(manager) + updater = WeightsUpdater(pipeline) + + def sync(): + seen = set() + for bucket in FSDPHfWeightIterator(args, student, diffusion_model_family="qwen_image21").iter_hf_weights(): + ok, message = updater.update_weights_from_tensor({"transformer": bucket}, target_modules=["transformer"]) + assert ok, message + for name, value in bucket: + torch.testing.assert_close(dict(native.named_parameters())[name], value, rtol=0, atol=0) + seen.add(name) + assert seen == set(dict(native.named_parameters())) + + embeddings = torch.randn(1, 3, 16, device="cuda") + noise = torch.randn(1, 4096, 4, device="cuda").bfloat16().float() + layout = build_layout([False] * 3, [(1, 64, 64)], config.axes_dims_rope, "cuda") + + @torch.no_grad() + def rollout(): + batch = Req( + prompt="tiny PDD", + height=1024, + width=1024, + num_inference_steps=8, + guidance_scale=1.0, + true_cfg_scale=1.0, + do_classifier_free_guidance=False, + prompt_embeds=[embeddings], + prompt_embeds_mask=[torch.ones(1, 3, device="cuda", dtype=torch.bool)], + latents=noise.clone(), + raw_latent_shape=list(noise.shape), + rollout=True, + rollout_sde_type="ode", + rollout_noise_level=0.0, + rollout_log_prob_no_const=True, + rollout_return_dit_trajectory=True, + rollout_return_denoising_env=True, + extra={"qwen21_positive": dict(layouts=[layout], prefix_caches=None), "qwen21_mu": 1.15}, + ) + batch = time_stage.forward(batch, server) + manager.begin_request([stage], batch, server) + data = stage.forward(batch, server).rollout_trajectory_data + trace = dataclasses.asdict(data.dit_trajectory) + trace["latents"] = trace["latents"][0] + sample = Sample(index=0, prompt="tiny PDD", seed=31) + sample.dit_trajectory = _parse_dit_trajectory(trace, deserialize_func=lambda x: x) + sample.denoising_env = _parse_denoising_env( + dataclasses.asdict(data.denoising_env), deserialize_func=lambda x: x + ) + return convert_samples_to_train_data(args, [sample])["train_data"][0] + + class Metrics: + def emit_mean(self, name, *, total, count): + assert name in SCHEMA, f"{name} is not declared in the FSDP metric schema" + + def predict(prepared): + with torch.autocast("cuda", dtype=torch.bfloat16): + return train_config.compute_noise_pred( + model=student, + latents_input=prepared.latents, + timesteps_input=prepared.timesteps_for_model, + pos_cond=prepared.pos_cond, + neg_cond=None, + joint_cond=None, + use_cfg=False, + cfg_batching=False, + guidance_scale=1.0, + true_cfg_scale=1.0, + ) + + @torch.no_grad() + def teacher_target(prepared): + # The actor's part: run the prepare hook's solver with the frozen teacher's forward. + def forward(latents, timesteps): + with torch.autocast("cuda", dtype=torch.bfloat16): + return train_config.compute_noise_pred( + model=teacher, + latents_input=latents, + timesteps_input=timesteps, + pos_cond=prepared.pos_cond, + neg_cond=None, + joint_cond=None, + use_cfg=False, + cfg_batching=False, + guidance_scale=1.0, + true_cfg_scale=None, + ) + + return prepared.teacher_solver(forward) + + ctx = DiffusionLossContext( + models={"transformer": student}, + train_pipeline_config=train_config, + sde_backend=None, + args=args, + forward_dtype=torch.bfloat16, + device=torch.device("cuda"), + rollout_id=0, + ) + + # One rollout, eight block-ordered updates, then sync back to the engine. + sync() + first = rollout() + for block in expand_train_pairs(ctx, [first]): + prepared = prepare_pdd_batch(ctx, [block], microbatch_id=0, optim_step_idx=0) + optimizer.zero_grad() + target = teacher_target(prepared) + loss = pdd_loss_formula( + ctx, + [block], + prepared, + new_pred=predict(prepared), + old_pred=None, + ref_pred=None, + teacher_pred=target, + metrics=Metrics(), + optim_step_idx=0, + train_output_inputs=[], + ) + loss.backward() + assert all(p.grad is None for p in teacher.parameters()) + optimizer.step() + sync() + + # 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"]) + 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) + # 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)) + torch.distributed.destroy_process_group() + + +if __name__ == "__main__": + if sys.argv[1:2] == ["--worker"]: + worker(Path(sys.argv[2])) + else: + sys.exit(pytest.main([__file__, "-v"])) diff --git a/tests/fast-gpu/test_lora_weight_sync.py b/tests/fast-gpu/test_lora_weight_sync.py index dfc02fc1a..056807543 100644 --- a/tests/fast-gpu/test_lora_weight_sync.py +++ b/tests/fast-gpu/test_lora_weight_sync.py @@ -32,7 +32,7 @@ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.buckets: list[list[tuple[str, torch.Tensor]]] = [] - def update_bucket_weights(self, named_tensors, target_module): + def update_bucket_weights(self, named_tensors, target_module, *, replace_weights=False): self.buckets.append([(name, tensor.clone()) for name, tensor in named_tensors]) @@ -43,8 +43,9 @@ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.buckets: list[list[tuple[str, torch.Tensor]]] = [] - def update_bucket_weights(self, named_tensors, target_module): + def update_bucket_weights(self, named_tensors, target_module, *, replace_weights=False): self.buckets.append([(name, tensor.clone()) for name, tensor in named_tensors]) + self.replaced = getattr(self, "replaced", []) + [replace_weights] def _make_peft_model(): @@ -123,6 +124,19 @@ def test_lora_ipc_bucket_keeps_ab_together(): torch.testing.assert_close(synced["proj.lora_B"], B) +def test_lora_ipc_pushes_full_trained_params_as_plain_weights_after_the_adapter(): + peft_model = _make_peft_model() + # A layer added after LoRA (as PDD's heads are) trains in full beside the adapter. + peft_model.get_base_model().head = torch.nn.Linear(16, 4).cuda() + updater = _CaptureLoRAIPCUpdater(_fake_args(1 << 30), {"transformer": peft_model}) + updater.update_weights() + assert updater.replaced == [False, True] + adapter, trained = ({name: t for name, t in bucket} for bucket in updater.buckets) + assert set(adapter) == {"proj.lora_A", "proj.lora_B"} + assert set(trained) == {"head.weight", "head.bias"} + torch.testing.assert_close(trained["head.weight"], peft_model.get_base_model().head.weight) + + if __name__ == "__main__": import sys diff --git a/tests/fast/backends/fsdp_utils/test_loss_hub_selection.py b/tests/fast/backends/fsdp_utils/test_loss_hub_selection.py index 0f1019464..ed64961db 100644 --- a/tests/fast/backends/fsdp_utils/test_loss_hub_selection.py +++ b/tests/fast/backends/fsdp_utils/test_loss_hub_selection.py @@ -48,6 +48,11 @@ formula="miles.backends.fsdp_utils.loss_hub.dmd2.critic_loss_formula", train_output="miles.backends.fsdp_utils.loss_hub.dmd2.score_last_step_samples", ), + ("pdd", "actor"): dict( + prepare="miles.backends.fsdp_utils.loss_hub.pdd.prepare_pdd_batch", + formula="miles.backends.fsdp_utils.loss_hub.pdd.pdd_loss_formula", + train_input="miles.distillation.integration.expand_train_pairs", + ), } diff --git a/tests/fast/backends/fsdp_utils/test_reference_models.py b/tests/fast/backends/fsdp_utils/test_reference_models.py index e90e271a2..5b9136036 100644 --- a/tests/fast/backends/fsdp_utils/test_reference_models.py +++ b/tests/fast/backends/fsdp_utils/test_reference_models.py @@ -103,11 +103,13 @@ def make_model_loader_args(): use_lora=True, update_weight_target_modules=["transformer", "transformer_2"], fsdp_master_dtype="fp32", + fsdp_param_dtype=None, fsdp_reduce_dtype="fp32", diffusion_forward_dtype="fp32", fsdp_attention_backend=None, gradient_checkpointing=False, offload_train=False, + custom_train_model_transform_path=None, ) @@ -156,6 +158,7 @@ def make_actor_forward_harness( ema_optimizer=None, teacher_models=None, teacher_guidance_scale=None, + teacher_solver=None, true_cfg_scale=None, ): observed = {} @@ -172,6 +175,7 @@ def make_actor_forward_harness( guidance_scale=1.0, true_cfg_scale=true_cfg_scale, teacher_guidance_scale=teacher_guidance_scale, + teacher_solver=teacher_solver, ) def prepare(ctx, batch, **kwargs): @@ -531,7 +535,7 @@ def test_the_trunk_hands_the_hooks_their_own_counters_and_the_one_list(): assert observed["formula_kwargs"]["train_output_inputs"] is train_output_inputs -def _teacher_harness(teacher_guidance_scale, *, with_teacher=True, true_cfg_scale=None): +def _teacher_harness(teacher_guidance_scale, *, with_teacher=True, true_cfg_scale=None, teacher_solver=None): actor, teacher = TinyComponent(), TinyComponent() order = [] actor.register_forward_hook(lambda *_: order.append("actor")) @@ -544,6 +548,7 @@ def _teacher_harness(teacher_guidance_scale, *, with_teacher=True, true_cfg_scal "none", teacher_models={"transformer": teacher} if with_teacher else None, teacher_guidance_scale=teacher_guidance_scale, + teacher_solver=teacher_solver, true_cfg_scale=true_cfg_scale, ) observed["order"] = order @@ -598,6 +603,30 @@ def test_an_unguided_teacher_runs_without_cfg(): ) +def test_a_teacher_solver_runs_the_teacher_on_its_own_states_before_the_actor(): + seen = [] + + def solver(forward): + # A two-stage solve: the second state depends on the first prediction. + first = forward({"visual": torch.full((2, 3), 2.0)}, {"visual": torch.full((2,), 0.5)})["visual"] + seen.append((first.requires_grad, torch.is_grad_enabled())) + return forward({"visual": torch.ones(2, 3) * first.mean()}, {"visual": torch.full((2,), 0.25)}) + + harness, observed, actor, teacher = _teacher_harness(1.0, teacher_solver=solver) + resharded = [] + + _run_forward(harness, reshard_model=resharded.append).backward() + + assert observed["order"] == ["teacher", "teacher", "actor"] + assert seen == [(False, False)] and resharded == [teacher] + with torch.no_grad(): + expected = teacher(torch.ones(2, 3) * teacher(torch.full((2, 3), 2.0)).mean()) + torch.testing.assert_close(observed["teacher_pred"], expected) + teacher_calls = [call for model, call in harness.train_pipeline_config.noise_pred_calls if model is teacher] + assert [float(call["timesteps_input"]["visual"][0]) for call in teacher_calls] == [0.5, 0.25] + assert actor.block.proj.weight.grad is not None and teacher.block.proj.weight.grad is None + + def test_no_teacher_forward_unless_the_prepare_hook_asks(): harness, observed, _, teacher = _teacher_harness(None) diff --git a/tests/fast/distillation/test_pdd.py b/tests/fast/distillation/test_pdd.py new file mode 100644 index 000000000..24b90f30d --- /dev/null +++ b/tests/fast/distillation/test_pdd.py @@ -0,0 +1,350 @@ +"""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.""" + +from tests.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=10, suite="stage-a-cpu", labels=[]) + +import copy +from types import SimpleNamespace + +import pytest +import torch +from torch import nn + +from miles.backends.fsdp_utils.loss_hub.pdd import pdd_loss_formula, prepare_pdd_batch +from miles.backends.fsdp_utils.loss_hub.types import DiffusionLossContext +from miles.backends.sglang_diffusion_utils.monkey_patches.patch_pdd_qwen_image21 import PDDProjection +from miles.distillation import integration +from miles.distillation.integration import ( + embedded_sigmas, + engine_timesteps, + expand_train_pairs, + install_student, + set_pdd_defaults, + validate_pdd_args, +) +from miles.distillation.pdd import ParallelLinear, block_update, interval_loss, teacher_mean_velocity +from miles.rollout import pdd_rollout + +GRID = torch.linspace(1, 0, 33) + + +@pytest.fixture(autouse=True) +def linear_grid(monkeypatch): + monkeypatch.setattr(integration, "make_grid", lambda *args: GRID) + + +# --- interval math ------------------------------------------------------------------------------------- + + +@pytest.mark.parametrize("descending", [False, True]) +def test_block_updates_follow_an_exact_linear_ode(descending): + """Analytic oracle dx/dt = a*x on a nonuniform grid: exact per-interval mean velocities integrate exactly.""" + grid = torch.tensor([0, 0.03, 0.11, 0.24, 0.42, 0.58, 0.73, 0.9, 1], dtype=torch.float64) + if descending: + grid = grid.flip(0) + a, x0 = torch.tensor(-0.7, dtype=torch.float64), torch.tensor([[1.3, -2.1]], dtype=torch.float64) + + def heads(state, time): + left, right = torch.exp(a * (grid[:-1] - time)), torch.exp(a * (grid[1:] - time)) + return ((right - left) / grid.diff())[:, None, None] * state + + x = x0 + for start in range(0, 8, 4): + x = block_update(x, heads(x, grid[start]), grid, start, start + 4) + torch.testing.assert_close(x, x0 * torch.exp(a * (grid[-1] - grid[0])), rtol=1e-12, atol=1e-12) + + +def test_teacher_target_is_a_detached_midpoint_step(): + weight = nn.Parameter(torch.tensor(0.5)) + calls = [] + + def teacher(state, time): + calls.append(torch.is_grad_enabled()) + return weight * state + time + + x, t, h = torch.tensor([[1.0, 2.0]], requires_grad=True), torch.tensor(0.7), torch.tensor(-0.2) + half = x.detach() + 0.5 * h * (0.5 * x.detach() + t) + target = teacher_mean_velocity(teacher, x, t, h) + torch.testing.assert_close(target, 0.5 * half + t + 0.5 * h) + assert calls == [False, False] and not target.requires_grad + + +# --- rollout side -------------------------------------------------------------------------------------- + + +def test_engine_steps_on_cached_heads_reproduce_every_interval(): + """One DiT forward per block; the block's other intervals step on the cached heads.""" + torch.manual_seed(8) + projection = PDDProjection(nn.Linear(3, 2)) + grid = GRID.square() + hidden, x = torch.randn(1, 5, 3), torch.randn(1, 5, 2) + for interval in range(32): + start = interval - interval % 4 + if interval == start: + torch.testing.assert_close(projection(hidden), projection.parallel(hidden)[0]) + block_state = x + x = x + projection.block[interval] * (grid[interval + 1] - grid[interval]) + expected = block_update(block_state, projection.parallel(hidden), grid, start, interval + 1) + torch.testing.assert_close(x, expected, rtol=1e-6, atol=1e-6) + + +def test_engine_timesteps_reproduce_the_trainer_bf16_sigma(): + # The native DiT embeds bf16(bf16(t) / 1000); the Diffusers trainer embeds bf16(sigma). + sigmas = torch.linspace(1, 0.01, 2000) + naive = embedded_sigmas(sigmas * 1000) != sigmas.bfloat16().float() + fixed = embedded_sigmas(engine_timesteps(sigmas)) != sigmas.bfloat16().float() + assert naive.float().mean() > 0.2 and fixed.float().mean() < 0.05 and not (fixed & ~naive).any() + + +def test_converter_accepts_only_the_full_trajectory_on_the_training_grid(): + sample = SimpleNamespace( + index=17, + 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) + pair = pdd_rollout.convert_samples_to_train_data(args, [sample])["train_data"][0] + torch.testing.assert_close(pair["pdd_trajectory"], sample.dit_trajectory.latents) + for field, value in [ + ("sigmas", GRID + 0.01), + ("latents", torch.randn(9, 4, 2)), + ("latents", torch.full((33, 4, 2), float("nan"))), + ]: + bad = copy.deepcopy(sample) + setattr(bad.dit_trajectory, field, value) + with pytest.raises(ValueError): + pdd_rollout.convert_samples_to_train_data(args, [bad]) + + +# --- trainer side -------------------------------------------------------------------------------------- + + +class Student(nn.Module): + def __init__(self): + super().__init__() + self.base = nn.Linear(2, 2) + self.head = ParallelLinear(nn.Linear(2, 2), 32) + + def forward(self, x, sigma): # [N, B, S, C] + return self.head(self.base(x) + sigma.reshape(-1, 1, 1)) + + +class Teacher(nn.Module): + def __init__(self): + super().__init__() + self.scale = nn.Parameter(torch.tensor(0.3), requires_grad=False) + self.inputs = [] + + def forward(self, x, sigma): + self.inputs.append(x.detach().clone()) + return self.scale * x + sigma.reshape(-1, 1, 1) + + +class Config: + def prepare_cond_kwargs(self, cond, device): + return cond + + +class Metrics: + def emit_mean(self, *args, **kwargs): + pass + + +def context(student, rollout=0): + args = SimpleNamespace(hf_checkpoint="unused", pdd_num_intervals=32, pdd_block_size=4, seed=42) + return DiffusionLossContext( + models={"transformer": student}, + train_pipeline_config=Config(), + sde_backend=None, + device=torch.device("cpu"), + forward_dtype=torch.float32, + args=args, + rollout_id=rollout, + ) + + +def rollout_pair(index): + return dict( + sample_index=index, pdd_trajectory=torch.randn(33, 4, 2), denoising_env=SimpleNamespace(pos_cond_kwargs={}) + ) + + +def test_eight_block_updates_from_rollout_states_match_an_independent_loop(): + torch.manual_seed(12) + student, teacher = Student(), Teacher() + reference = copy.deepcopy(student) + opt, refopt = (torch.optim.AdamW(m.parameters(), lr=1e-3, weight_decay=0) for m in (student, reference)) + ctx = context(student) + pairs = [rollout_pair(i) for i in (2, 9)] + expanded = expand_train_pairs(ctx, pairs) + assert [p["pdd_start"] for p in expanded] == [s for s in range(0, 32, 4) for _ in pairs] + for step in range(8): + opt.zero_grad() + refopt.zero_grad() + for pair in expanded[step * 2 : (step + 1) * 2]: + prepared = prepare_pdd_batch(ctx, [pair], microbatch_id=0, optim_step_idx=0) + 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) + # 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) + loss = pdd_loss_formula( + ctx, + [pair], + prepared, + new_pred={"visual": student(x, sigma).permute(1, 2, 0, 3).flatten(2)}, + old_pred=None, + ref_pred=None, + teacher_pred=target, + metrics=Metrics(), + optim_step_idx=0, + train_output_inputs=[], + ) + x_k = pair["pdd_trajectory"][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) + (loss / 2).backward() + (refloss / 2).backward() + opt.step() + refopt.step() + assert teacher.scale.grad is None + for a, b in zip(student.parameters(), reference.parameters(), strict=True): + torch.testing.assert_close(a, b, rtol=0, atol=0) + + +def test_interval_choice_depends_only_on_rollout_lane_and_block(): + pair = dict(rollout_pair(99), pdd_start=0) + + def choose(rollout): + return prepare_pdd_batch(context(Student(), rollout), [pair], microbatch_id=0, optim_step_idx=0).extras[ + "selected" + ] + + chosen = choose(7) + torch.randn(500) # process RNG must not change a resumed rollout's choice + assert choose(7) == chosen and {choose(r) for r in range(32)} == {0, 1, 2, 3} + + +def test_lora_student_trains_adapters_and_full_heads_and_checkpoints_both(): + from peft import LoraConfig, get_peft_model + + from miles.backends.fsdp_utils.checkpoint import ModelState + + class Tiny(nn.Module): + def __init__(self): + super().__init__() + self.to_q = nn.Linear(4, 4) + self.proj_out = nn.Linear(4, 2) + + 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)) + 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} + assert trainable == { + "base_model.model.to_q.lora_A.default.weight", + "base_model.model.to_q.lora_B.default.weight", + "base_model.model.proj_out.parallel.weight", + "base_model.model.proj_out.parallel.bias", + } + state = ModelState(model, lora_only=True) + assert {name for name in dict(model.named_parameters()) if state._saved(name)} == trainable + + +# --- arguments ----------------------------------------------------------------------------------------- + + +def configured(**overrides): + """set_default_diffusion_args -> user overrides stand -> miles_validate_args, as in parse_args.""" + args = SimpleNamespace( + **dict.fromkeys( + ( + "train_only use_ema ref_load teacher_lora_adapter_paths lora_adapter_paths micro_batch_size_sample " + "diffusion_recompute_old_log_prob diffusion_kl_beta teacher_load diffusion_step_strategy_path " + "custom_generate_function_path group_rm rollout_patch_group custom_convert_samples_to_train_data_path " + "custom_rm_path custom_train_model_transform_path fsdp_param_dtype num_steps_per_rollout " + "global_batch_size rollout_return_full_trajectory" + ).split() + ), + diffusion_model_family="qwen_image21", + diffusion_task="t2i", + train_backend="fsdp", + update_weight_target_modules=["transformer"], + pdd_num_intervals=32, + pdd_block_size=4, + diffusion_height=1024, + diffusion_width=1024, + micro_batch_size=1, + sequence_parallel_size=1, + use_lora=True, + colocate=True, + lora_ipc_weight_sync=True, + sglang_lora_merge_mode="dynamic", + ref_mode="none", + diffusion_guidance_scale=1.0, + diffusion_true_cfg_scale=1.0, + prompt_data="train.jsonl", + rollout_global_dataset=True, + n_samples_per_prompt=1, + fsdp_master_dtype="fp32", + diffusion_forward_dtype="bf16", + hf_checkpoint="model", + diffusion_num_steps=8, + diffusion_eval_num_steps=8, + diffusion_sde_type="ode", + diffusion_noise_level=0, + rollout_num_gpus_per_engine=1, + rollout_microgroup_size=1, + sglang_dit_precision="fp32", + rollout_function_path="miles.rollout.sglang_rollout.generate_rollout", + rollout_batch_size=8, + ) + for name, value in overrides.items(): + setattr(args, name, value) + set_pdd_defaults(args) + args.rollout_patch_groups = [name for name in (args.rollout_patch_group or "").split(",") if name] + validate_pdd_args(args) + return args + + +def test_defaults_select_the_sglang_rollout_and_eight_updates_per_rollout(): + from miles.backends.fsdp_utils.loss_hub import LOSS_HOOKS + + args = configured() + assert (args.global_batch_size, args.num_steps_per_rollout) == (8, 8) + assert args.teacher_load == args.hf_checkpoint and args.fsdp_param_dtype == "fp32" + assert args.rollout_patch_groups == ["pdd_qwen_image21"] and args.rollout_return_full_trajectory + assert args.custom_train_model_transform_path.endswith("integration.install_student") + hooks = LOSS_HOOKS[("pdd", "actor")] + assert (hooks.prepare, hooks.formula, hooks.train_input) == ( + prepare_pdd_batch, + pdd_loss_formula, + expand_train_pairs, + ) + + +@pytest.mark.parametrize( + "name,value", + [ + ("use_lora", False), + ("sglang_lora_merge_mode", "merge"), + ("lora_ipc_weight_sync", False), + ("pdd_block_size", 8), + ("global_batch_size", 1), + ("diffusion_guidance_scale", 4), + ("diffusion_height", 512), + ("sglang_dit_precision", "bf16"), + ], +) +def test_unvalidated_modes_fail_before_gpu_load(name, value): + with pytest.raises(ValueError): + configured(**{name: value})