From 6429724c7823e0eea4f2c716fdbfbd144b1baf27 Mon Sep 17 00:00:00 2001 From: niehen6174 <1639206518@qq.com> Date: Fri, 13 Nov 2026 19:31:12 +0800 Subject: [PATCH 1/3] feat(pdd): add Qwen-Image 2.1 PDD training with a LoRA student from SGLang rollouts Parallel Decoding Distillation (`--loss-type pdd`): SGLang rolls out an 8-step student whose output layer is 32 interval heads, the FSDP actor trains it against the frozen teacher's midpoint velocity, and weight sync closes the loop. - Rollout: the `pdd_qwen_image21` patch group steps all 32 intervals with one DiT forward per 4-interval block (heads cached), so the trajectory carries every interval's start state; the trainer never re-simulates the trajectory. - Training: each trajectory expands into eight block-ordered updates (loss-hub train-input hook). Update j recomputes the heads from the rollout state at block j; the prepare hook hands the actor a `teacher_solver`, so the teacher's midpoint solve from the rollout's sampled-interval state runs in the actor like any other teacher forward. - LoRA student: adapters on the backbone, heads trained in full. The model-transform hook (`--custom-train-model-transform-path`) now runs after LoRA so the heads it adds stay trainable; LoRA checkpoints keep them, and LoRA weight sync pushes them as plain weights after the adapter. The engine applies the adapter unmerged (merging into BF16 weights rounds a small update away). - Generic: `--fsdp-param-dtype`; an explicit global batch size is allowed when a train-input hook defines the per-step samples; the LR schedule counts num_rollout x num_steps_per_rollout optimizer steps. Docs: docs/developer/pdd.md. Tests: CPU loss/rollout/integration tests, FSDP one/two-rank parity against an unsharded reference, and an SGLang closed-loop smoke. --- docs/developer/pdd.md | 139 +++++++ docs/user-guide/cli-reference.md | 5 +- miles/backends/fsdp_utils/actor.py | 25 +- miles/backends/fsdp_utils/checkpoint.py | 15 +- .../diffusion_update_weight_utils.py | 21 +- .../backends/fsdp_utils/hf_weight_iterator.py | 14 +- .../backends/fsdp_utils/loss_hub/__init__.py | 3 + miles/backends/fsdp_utils/loss_hub/pdd.py | 133 +++++++ miles/backends/fsdp_utils/loss_hub/types.py | 5 + miles/backends/fsdp_utils/lr_scheduler.py | 2 +- miles/backends/fsdp_utils/metrics.py | 2 + miles/backends/fsdp_utils/model_loader.py | 10 +- .../monkey_patches/__init__.py | 8 + .../monkey_patches/patch_pdd_qwen_image21.py | 114 ++++++ .../hf_weight_iterator/__init__.py | 12 + miles/distillation/__init__.py | 1 + miles/distillation/integration.py | 250 +++++++++++++ miles/distillation/pdd.py | 121 +++++++ miles/rollout/pdd_rollout.py | 48 +++ miles/utils/arguments.py | 44 ++- .../_param_dtype_map_integration_worker.py | 1 + .../backends/fsdp_utils/_pdd_worker.py | 230 ++++++++++++ .../fast-gpu/backends/fsdp_utils/test_pdd.py | 43 +++ .../test_pdd_sglang_loop.py | 285 +++++++++++++++ tests/fast-gpu/test_lora_weight_sync.py | 18 +- .../fsdp_utils/test_loss_hub_selection.py | 5 + .../fsdp_utils/test_reference_models.py | 31 +- .../test_miles_pdd_integration.py | 342 ++++++++++++++++++ tests/fast/distillation/test_pdd.py | 86 +++++ tests/fast/distillation/test_pdd_rollout.py | 83 +++++ 30 files changed, 2071 insertions(+), 25 deletions(-) create mode 100644 docs/developer/pdd.md create mode 100644 miles/backends/fsdp_utils/loss_hub/pdd.py create mode 100644 miles/backends/sglang_diffusion_utils/monkey_patches/patch_pdd_qwen_image21.py create mode 100644 miles/distillation/__init__.py create mode 100644 miles/distillation/integration.py create mode 100644 miles/distillation/pdd.py create mode 100644 miles/rollout/pdd_rollout.py create mode 100644 tests/fast-gpu/backends/fsdp_utils/_pdd_worker.py create mode 100644 tests/fast-gpu/backends/fsdp_utils/test_pdd.py create mode 100644 tests/fast-gpu/backends/sglang_diffusion_utils/test_pdd_sglang_loop.py create mode 100644 tests/fast/distillation/test_miles_pdd_integration.py create mode 100644 tests/fast/distillation/test_pdd.py create mode 100644 tests/fast/distillation/test_pdd_rollout.py diff --git a/docs/developer/pdd.md b/docs/developer/pdd.md new file mode 100644 index 000000000..439a26d6e --- /dev/null +++ b/docs/developer/pdd.md @@ -0,0 +1,139 @@ +# 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 per latent stream, 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. + +| Family | Task | Streams | Grid | Engine weights | FSDP all-gather | +|---|---|---|---|---|---| +| `qwen_image21` | t2i, 1024 × 1024 | visual | the scheduler's shifted grid | FP32 | FP32, 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 per stream) for eight DiT forwards. +2. After data-parallel splitting, each trajectory expands into its eight blocks. +3. Update j recomputes the heads from the rollout state at block j and samples one + of its four intervals. The prepare hook asks the actor for the frozen teacher's + midpoint velocity from the rollout's state at that interval, one joint teacher call + per midpoint stage for all streams; the loss regresses the selected head of every + stream on it and steps once. Block j's states were produced j updates before the + weights it trains. +4. After the eight updates the driver synchronizes the student back to SGLang: the + LoRA adapter, then the heads as plain weights. + +The student's output layers are replicated into heads after LoRA is applied and before +FSDP wrapping and optimizer creation, so the heads train in full beside the adapters and +LoRA checkpoints keep them; all heads start from the base model's output layer. + +`--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. What differs per model family lives in `PDD_FAMILIES`: + +| Hook | PDD default | +|---|---| +| `--custom-train-model-transform-path` | `install_student`: each stream's output layer as 32 heads, after LoRA | +| loss hub train input | `expand_train_pairs`: trajectory → eight block pairs | +| loss hub prepare / formula | `loss_hub/pdd.py`; the teacher runs in the actor through `PreparedBatch.teacher_solver` | +| `--custom-convert-samples-to-train-data-path` / `--custom-rm-path` | `miles/rollout/pdd_rollout.py` | +| `--rollout-patch-group` | `pdd_qwen_image21` | +| `--fsdp-param-dtype` | `fp32` | + +`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 +python -m pytest tests/fast-gpu/backends/fsdp_utils/test_pdd.py +python -m pytest tests/fast-gpu/backends/sglang_diffusion_utils/test_pdd_sglang_loop.py +``` + +CPU tests cover detached teacher supervision, selected-head gradients, signed +nonuniform grids, eight block updates from rollout states against an independent +optimizer loop (the test plays the actor's teacher solve), the engine's cached +interval steps, trajectory validation, timestep matching and unsupported configurations. The FSDP +GPU test compares tiny-model updates with an unsharded reference on one and two +ranks, loading the student through the model-transform hook (two-rank case skips +with fewer GPUs). The SGLang GPU smoke runs real Qwen-Image 2.1 native stages, the +response parser, one-rank FSDP, 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. +All GPU cases skip when CUDA is unavailable. + +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..8fda0acf9 --- /dev/null +++ b/miles/backends/fsdp_utils/loss_hub/pdd.py @@ -0,0 +1,133 @@ +"""PDD prepare/loss hooks. The FSDP actor owns every DiT forward: the student's, and the +teacher's midpoint solve from the rollout's interval state, requested by prepare. + +Every latent stream of the family moves on its own grid; one +sampled interval and one joint teacher call cover all streams. +""" + +import torch + +from miles.distillation.integration import pdd_family +from miles.distillation.pdd import block_update, interval_loss, teacher_mean_velocity +from miles.utils.hash_utils import stable_hash + +from .types import PreparedBatch + + +def prepare_pdd_batch(ctx, batch, *, microbatch_id, optim_step_idx, pad_to_len=None): + if len(batch) != 1 or pad_to_len is not None: + raise ValueError("PDD supports one unpadded sample per microbatch") + pair = batch[0] + args = ctx.args + family = pdd_family(args) + start, lane = pair["pdd_start"], pair["sample_index"] + if start not in range(0, args.pdd_num_intervals, args.pdd_block_size): + raise ValueError("Invalid PDD rollout block index") + grids = {stream: grid.to(ctx.device) for stream, grid in family.grids(args).items()} + generator = torch.Generator().manual_seed(stable_hash("pdd-interval", args.seed, ctx.rollout_id, lane, start)) + selected = int(torch.randint(start, start + args.pdd_block_size, (), generator=generator)) + # The block and the teacher both start from fixed-weight SGLang rollout states (indexed by interval). + trajectory = pair["pdd_trajectory"] + if set(trajectory) != set(family.heads): + raise ValueError(f"PDD rollout streams {sorted(trajectory)} differ from {sorted(family.heads)}") + states, x_selected = ( + {stream: trajectory[stream][i].to(ctx.device).unsqueeze(0).float() for stream in family.heads} + for i in (start, selected) + ) + if not all(torch.isfinite(state).all() for state in states.values()): + raise ValueError("Invalid PDD rollout latent values") + condition = ctx.train_pipeline_config.prepare_cond_kwargs(pair["denoising_env"].pos_cond_kwargs, ctx.device) + # FP32 conditioning boundary; autocast controls matmuls. + 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() + } + condition.update(family.cond_extras) + + def time(time_fn, index): + return {stream: time_fn(args, stream, grid[index].reshape(1)).to(ctx.device) for stream, grid in grids.items()} + + def solve(forward): + def teacher(x, sigma): + timesteps = { + stream: family.teacher_time(args, stream, value.reshape(1)) for stream, value in sigma.items() + } + pred = forward(x, timesteps) + return {stream: pred[stream].float() for stream in x} + + sigma = {stream: grid[selected] for stream, grid in grids.items()} + delta = {stream: grid.diff()[selected] for stream, grid in grids.items()} + return teacher_mean_velocity(teacher, x_selected, sigma, delta, solver="midpoint") + + return PreparedBatch( + latents=states, + timesteps={stream: grid[start].reshape(1) for stream, grid in grids.items()}, + timesteps_for_model=time(family.model_time, start), + 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, "grids": grids}, + 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, grids = (prepared.extras[k] for k in ("start", "selected", "grids")) + end = start + ctx.args.pdd_block_size + per_sample_loss = 0 + for stream, x in prepared.latents.items(): + raw = new_pred[stream] + if raw.shape != (*x.shape[:-1], n * x.shape[-1]): + raise ValueError(f"PDD student {stream} output shape does not match the parallel heads") + predictions = raw.reshape(*x.shape[:-1], n, x.shape[-1]).permute(2, 0, 1, 3) + stream_loss = interval_loss(predictions, selected, teacher_pred[stream]) + if not torch.isfinite(stream_loss).all(): + raise FloatingPointError(f"nonfinite PDD {stream} loss") + per_sample_loss = per_sample_loss + stream_loss + with torch.no_grad(): + following = block_update(x, predictions, grids[stream], start, end).detach() + if not torch.isfinite(following).all(): + raise FloatingPointError(f"nonfinite PDD {stream} trajectory") + # Trainer vs. engine next state; later blocks also include rollout staleness. + expected = batch[0]["pdd_trajectory"][stream][end].to(ctx.device).unsqueeze(0).float() + error = (following - expected).abs() + prefix = "pdd" if stream == "visual" else f"pdd_{stream}" + metrics.emit_mean(f"{prefix}_next_latent_mae", total=error.sum(), count=error.numel()) + relative = error.mean() / (expected - x).abs().mean().clamp_min(1e-6) + metrics.emit_mean(f"{prefix}_update_relative_error", total=relative, count=1) + if len(prepared.latents) > 1: + metrics.emit_mean(f"pdd_{stream}_loss", total=stream_loss.sum(), count=len(batch)) + with torch.no_grad(): + metrics.emit_mean("loss", total=per_sample_loss.sum().detach(), 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..4f0aaaaef --- /dev/null +++ b/miles/backends/sglang_diffusion_utils/monkey_patches/patch_pdd_qwen_image21.py @@ -0,0 +1,114 @@ +"""Experimental head-only PDD rollout. Keep the native DiT and rollout scheduler. + +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 engine_timesteps, make_grid +from miles.distillation.pdd import ParallelLinear + + +class PDDProjection(nn.Module): + def __init__(self, source): + super().__init__() + self.parallel = ParallelLinear(source, 32) + 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) != (1024, 1024, 8): + raise ValueError("PDD requires 1024x1024 and 8 steps") + batch = original_time(self, batch, server_args) + grid = make_grid(server_args.model_path, 32, 4096, 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 = 32 + 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 % 4 == 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..dcfdc4708 --- /dev/null +++ b/miles/distillation/integration.py @@ -0,0 +1,250 @@ +"""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``. What +differs per model family (latent streams, sigma grids, time inputs, rollout patch) +lives in ``PDD_FAMILIES``. +""" + +import functools +from collections.abc import Callable +from dataclasses import dataclass, field +from typing import Any + +import torch + +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) + + +@dataclass(frozen=True) +class PDDFamily: + """What PDD needs from one model family, looked up by ``--diffusion-model-family``. + + ``heads`` maps each latent stream to the Diffusers transformer's output layer that becomes N heads; + ``grids(args)`` gives each stream's (N+1)-point sigma grid; ``model_time`` / ``teacher_time`` turn a grid + sigma into the student's and the teacher's ``timesteps_for_model``; ``split_states`` cuts the rollout's + per-interval states into streams; ``validate`` checks the family's rollout settings. + """ + + task: str + heads: dict[str, str] + patch_group: str + engine_precision: str + # None keeps the family's FSDP plan (e.g. FP32 heads over a BF16 all-gather). + fsdp_param_dtype: str | None + grids: Callable[[Any], dict[str, torch.Tensor]] + model_time: Callable[[Any, str, torch.Tensor], torch.Tensor] + teacher_time: Callable[[Any, str, torch.Tensor], torch.Tensor] + split_states: Callable[[torch.Tensor, Any], dict[str, torch.Tensor]] + validate: Callable[[Any], None] + cond_extras: dict[str, Any] = field(default_factory=dict) + + +def _qwen_validate(args): + if args.diffusion_height != 1024 or args.diffusion_width != 1024: + raise ValueError("PDD requires 1024 x 1024 for Qwen-Image 2.1") + + +PDD_FAMILIES = { + "qwen_image21": PDDFamily( + task="t2i", + heads={"visual": "proj_out"}, + patch_group="pdd_qwen_image21", + engine_precision="fp32", + # Gathered student weights stay FP32 (head biases, norms); autocast handles matmuls. + fsdp_param_dtype="fp32", + grids=lambda args: { + "visual": make_grid(args.hf_checkpoint, args.pdd_num_intervals, (args.diffusion_height // 16) ** 2) + }, + # The student sees the time value SGLang embedded; the grid dynamics stay unchanged. + model_time=lambda args, stream, sigma: embedded_sigmas(engine_timesteps(sigma)), + teacher_time=lambda args, stream, sigma: sigma, + split_states=lambda states, env: {"visual": states}, + validate=_qwen_validate, + ), +} + + +def pdd_family(args): + try: + return PDD_FAMILIES[args.diffusion_model_family] + except KeyError: + raise ValueError(f"PDD supports --diffusion-model-family {sorted(PDD_FAMILIES)}") from None + + +def install_student(model, args): + """``--custom-train-model-transform-path`` hook: each stream's output layer becomes N heads, trained in + full beside the backbone's LoRA adapters.""" + for attr in pdd_family(args).heads.values(): + layer = getattr(model, attr) + if not isinstance(layer, torch.nn.Linear): + raise ValueError(f"PDD needs an unmodified {attr} output layer") + setattr(model, attr, TokenParallelProjection(layer, args.pdd_num_intervals)) + + +def expand_trajectories(pairs, *, intervals, block_size): + """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 + family = PDD_FAMILIES.get(args.diffusion_model_family) + if family is not None: + if args.rollout_patch_group is None: + args.rollout_patch_group = family.patch_group + if args.fsdp_param_dtype is None: + args.fsdp_param_dtype = family.fsdp_param_dtype + if args.teacher_load is None: + args.teacher_load = args.hf_checkpoint + args.rollout_return_full_trajectory = True + # 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.""" + family = pdd_family(args) + if args.diffusion_task != family.task: + raise ValueError(f"PDD supports {args.diffusion_model_family} {family.task} only") + family.validate(args) + if args.train_only or args.train_backend != "fsdp": + raise ValueError("PDD trains on FSDP from SGLang rollouts; drop --train-only") + if args.update_weight_target_modules != ["transformer"]: + raise ValueError("PDD trains only the transformer component") + if (args.pdd_num_intervals, args.pdd_block_size) != (32, 4): + 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 != family.engine_precision: + raise ValueError(f"PDD requires --sglang-dit-precision {family.engine_precision}") + if args.fsdp_param_dtype != family.fsdp_param_dtype: + raise ValueError(f"PDD requires --fsdp-param-dtype {family.fsdp_param_dtype}") + if args.diffusion_step_strategy_path or args.custom_generate_function_path or args.group_rm: + raise ValueError("PDD requires the standard full-trajectory rollout without custom generation/group RM") + if args.rollout_patch_groups != [family.patch_group]: + raise ValueError(f"PDD requires only the {family.patch_group} rollout patch group") + for key, value in {**_HOOK_DEFAULTS, "rollout_function_path": _DIFFUSION_ROLLOUT}.items(): + if getattr(args, key) != value: + raise ValueError(f"PDD requires {key}={value}") + 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..6c1ac3afc --- /dev/null +++ b/miles/distillation/pdd.py @@ -0,0 +1,121 @@ +"""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 + + +def _each(fn, *trees): + """Apply ``fn`` leafwise over tensors or same-keyed dicts of tensors (one entry per latent stream).""" + if isinstance(trees[0], dict): + return {key: fn(*(tree[key] for tree in trees)) for key in trees[0]} + return fn(*trees) + + +@torch.no_grad() +def teacher_mean_velocity(teacher: Callable, x, time, delta, solver: str = "midpoint"): + """Teacher closure includes conditioning/CFG; never build a teacher gradient graph. + + ``x``, ``time`` and ``delta`` are tensors, or dicts keyed by latent stream for a joint + model whose streams move on their own grids in one teacher call. + """ + if solver not in {"euler", "midpoint"}: + raise ValueError("solver must be euler or midpoint") + + def call(state, t): + velocity = teacher(state, t) + pairs = [(velocity[k], state[k]) for k in state] if isinstance(state, dict) else [(velocity, state)] + if any(v.shape != s.shape for v, s in pairs): + raise ValueError("teacher output must match the latent shape exactly") + return velocity + + x = _each(torch.Tensor.detach, x) + velocity = call(x, time) + if solver == "midpoint": + velocity = call( + _each(lambda s, d, v: s + 0.5 * d * v, x, delta, velocity), + _each(lambda t, d: t + 0.5 * d, time, delta), + ) + return _each(torch.Tensor.detach, velocity) + + +def block_update(x: torch.Tensor, predictions: torch.Tensor, grid: torch.Tensor, start: int, end: int) -> torch.Tensor: + """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) + + +def pdd_loss( + predictions: torch.Tensor, + x_start: torch.Tensor, + grid: torch.Tensor, + start: int, + selected: int, + teacher: Callable, + *, + x_selected: torch.Tensor | None = None, + solver: str = "midpoint", +) -> torch.Tensor: + """Per-sample loss for one uniformly sampled intra-block interval, shared across the microbatch. + + The caller supplies predictions from ONE student forward at (x_start, grid[start]). + The teacher starts from ``x_selected`` (e.g. the rollout's state at that interval), or + else from the earlier heads' update under stop-gradient. Only the selected head and + its shared backbone receive gradients from this Monte Carlo loss. + """ + validate_grid(grid) + if not 0 <= start <= selected < len(grid) - 1: + raise ValueError("require 0 <= start <= selected < num_intervals") + with torch.no_grad(): + if x_selected is None: + x_selected = block_update(x_start.detach(), predictions.detach(), grid, start, selected) + target = teacher_mean_velocity(teacher, x_selected, grid[selected], grid.diff()[selected], solver) + return interval_loss(predictions, selected, target) diff --git a/miles/rollout/pdd_rollout.py b/miles/rollout/pdd_rollout.py new file mode 100644 index 000000000..30b1c80ab --- /dev/null +++ b/miles/rollout/pdd_rollout.py @@ -0,0 +1,48 @@ +"""PDD rollout hooks: validate SGLang trajectories for the block-ordered updates. + +SGLang returns the start state of all 32 intervals plus the endpoint, per latent +stream (the family's ``split_states`` cuts a packed trajectory into streams). 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_family + + +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): + family = pdd_family(args) + grids = family.grids(args) + states_count = args.pdd_num_intervals + 1 + pairs = [] + for sample in samples: + traj, env = sample.dit_trajectory, sample.denoising_env + if traj is None or env is None or env.pos_cond_kwargs is None: + raise ValueError("PDD requires SGLang trajectory and positive conditioning") + if traj.sigmas is None or not torch.equal(traj.sigmas.cpu().float(), grids["visual"]): + 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") + streams = family.split_states(states, env) + pairs.append(dict(sample_index=sample.index, pdd_trajectory=streams, 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/fsdp_utils/_pdd_worker.py b/tests/fast-gpu/backends/fsdp_utils/_pdd_worker.py new file mode 100644 index 000000000..87ecd596d --- /dev/null +++ b/tests/fast-gpu/backends/fsdp_utils/_pdd_worker.py @@ -0,0 +1,230 @@ +"""Tiny-Qwen FSDP parity for the Miles PDD path, loaded through PDD's generic loader hooks. + +Run with torchrun --standalone --nproc-per-node=1 (or 2). Uses a random tiny model; +this verifies FSDP numerics, not pretrained image quality. +""" + +import argparse +import json +import os +from pathlib import Path +from types import SimpleNamespace + +import torch +import torch.distributed as dist +from diffusers import QwenImage21Transformer2DModel +from torch.distributed.checkpoint.state_dict import StateDictOptions, get_model_state_dict +from torch.distributed.device_mesh import init_device_mesh + +from miles.backends.fsdp_utils.configs.qwen_image21 import QwenImage21TrainPipelineConfig +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.model_backend import DiffusersModelBackend +from miles.backends.fsdp_utils.model_loader import load_fsdp_models +from miles.distillation import integration +from miles.distillation.integration import install_student +from miles.distillation.pdd import pdd_loss + + +def tiny(dtype=torch.float32): + torch.manual_seed(72) + return QwenImage21Transformer2DModel( + in_channels=4, + out_channels=4, + num_layers=1, + attention_head_dim=16, + num_attention_heads=2, + context_in_dim=16, + axes_dims_rope=(4, 6, 6), + mlp_ratio=2, + ).to(dtype=dtype) + + +class Backend(DiffusersModelBackend): + def load_component(self, component, *, checkpoint_path, master_dtype, materialize_weights): + return tiny(master_dtype) + + +class Metrics: + def emit_mean(self, *args, **kwargs): + pass + + +def full(model): + return get_model_state_dict(model, options=StateDictOptions(full_state_dict=True)) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--output", type=Path, required=True) + cli = parser.parse_args() + rank = int(os.environ["LOCAL_RANK"]) + torch.cuda.set_device(rank) + dist.init_process_group("nccl", device_id=torch.device("cuda", rank)) + device = torch.device("cuda", rank) + mesh = init_device_mesh("cuda", (dist.get_world_size(),), mesh_dim_names=("fsdp",)) + parallel = SimpleNamespace(get_mesh=lambda name: mesh, get_optional_mesh=lambda name: None) + args = SimpleNamespace( + diffusion_model_family="qwen_image21", + fsdp_master_dtype="fp32", + fsdp_param_dtype="fp32", + fsdp_reduce_dtype="fp32", + custom_train_model_transform_path="miles.distillation.integration.install_student", + diffusion_forward_dtype="bf16", + update_weight_target_modules=["transformer"], + fsdp_attention_backend=None, + gradient_checkpointing=True, + use_lora=False, + pdd_num_intervals=32, + pdd_block_size=4, + offload_train=False, + diffusion_height=64, + diffusion_width=64, + seed=42, + hf_checkpoint="tiny", + ) + config = QwenImage21TrainPipelineConfig() + config.configure(args) + config.prepare_cond_kwargs = lambda cond, device: cond # synthetic conditioning, not a rollout env + backend = Backend(config) + models = load_fsdp_models(args, backend, config, parallel, checkpoint_path="tiny", trainable=True) + teachers = load_fsdp_models(args, backend, config, parallel, checkpoint_path="tiny", trainable=False) + model = models["transformer"] + teacher = teachers["transformer"] + reference = tiny().to(device) + install_student(reference, args) + reference.load_state_dict(full(model)) + refteacher = tiny().to(device).eval().requires_grad_(False) + refteacher.load_state_dict(full(teacher)) + optimizer = torch.optim.AdamW(model.parameters(), lr=1e-4, weight_decay=0, foreach=False) + refopt = torch.optim.AdamW(reference.parameters(), lr=1e-4, weight_decay=0, foreach=False) + grid = torch.linspace(1, 0, 33, device=device) + integration.make_grid = lambda *args: grid # the tiny model has no scheduler config + torch.manual_seed(100 + rank) + cond = { + "encoder_hidden_states": torch.randn(1, 3, 16, device=device), + "encoder_hidden_states_mask": None, + "img_mask": torch.tensor([[False] * 3 + [True] * 4], device=device), + "img_shapes": [[(1, 4, 4)]], + } + # A rollout trajectory: every interval start plus the endpoint, BF16-rounded like the engine's noise. + trajectory = torch.randn(33, 16, 4).bfloat16().float() + env = SimpleNamespace(pos_cond_kwargs=cond) + ctx = DiffusionLossContext( + models=models, + train_pipeline_config=config, + sde_backend=None, + args=args, + forward_dtype=torch.bfloat16, + device=device, + ) + max_output = 0.0 + max_grad = 0.0 + for start in range(0, 32, 4): + optimizer.zero_grad() + refopt.zero_grad() + pair = { + "sample_index": rank, + "pdd_start": start, + "pdd_trajectory": {"visual": trajectory}, + "denoising_env": env, + } + prepared = prepare_pdd_batch(ctx, [pair], microbatch_id=0, optim_step_idx=0) + x = prepared.latents["visual"] + torch.testing.assert_close(x[0].cpu(), trajectory[start], rtol=0, atol=0) + with torch.autocast("cuda", dtype=torch.bfloat16): + + def teacher_forward(latents, timesteps): + # The actor's teacher forward: the sharded frozen teacher on this batch's conditioning. + return config.compute_noise_pred( + model=teacher, + latents_input=latents, + timesteps_input=timesteps, + pos_cond=cond, + neg_cond=None, + joint_cond=None, + use_cfg=False, + cfg_batching=False, + guidance_scale=1.0, + true_cfg_scale=None, + ) + + with torch.no_grad(): + target = prepared.teacher_solver(teacher_forward) + pred = config.compute_noise_pred( + model=model, + latents_input={"visual": x}, + timesteps_input=prepared.timesteps_for_model, + pos_cond=cond, + neg_cond=None, + joint_cond=None, + use_cfg=False, + cfg_batching=False, + guidance_scale=1.0, + true_cfg_scale=1.0, + ) + # Unsharded student: keep the image-token tail, split into [head, batch, token, channel]. + model_sigma = prepared.timesteps_for_model["visual"] + refpred = reference(hidden_states=x, timestep=model_sigma, return_dict=False, **cond)[0] + refpred = refpred[:, -16:].reshape(1, 16, 32, 4).permute(2, 0, 1, 3) + loss = pdd_loss_formula( + ctx, + [pair], + prepared, + new_pred=pred, + old_pred=None, + ref_pred=None, + teacher_pred=target, + metrics=Metrics(), + optim_step_idx=0, + train_output_inputs=[], + ) + + def tf(state, sigma): + return refteacher(hidden_states=state, timestep=sigma.expand(1), return_dict=False, **cond)[0][ + :, -16: + ].float() + + selected = prepared.extras["selected"] + x_selected = trajectory[selected].to(device).unsqueeze(0) + refloss = pdd_loss(refpred, x, grid, start, selected, tf, x_selected=x_selected).sum() + rawref = refpred.permute(1, 2, 0, 3).flatten(2) + err = (pred["visual"] - rawref).abs().max().item() + max_output = max(max_output, err) + torch.testing.assert_close(pred["visual"], rawref, rtol=0, atol=0) + torch.testing.assert_close(loss, refloss, rtol=0, atol=0) + loss.backward() + refloss.backward() + for (name, p), (rname, r) in zip(model.named_parameters(), reference.named_parameters(), strict=True): + assert name == rname and (p.grad is None) == (r.grad is None), name + if p.grad is not None: + dist.all_reduce(r.grad) + r.grad.div_(dist.get_world_size()) + grad = p.grad.full_tensor() + max_grad = max(max_grad, (grad - r.grad).abs().max().item()) + # Losses match bitwise; the BF16-autocast backward sums in a different order under FSDP + # (observed up to 1.3e-3 of the largest entry, well under one BF16 ulp). + scale = r.grad.abs().max().item() + torch.testing.assert_close(grad, r.grad, rtol=2e-5, atol=2e-6 + 5e-3 * scale, msg=name) + optimizer.step() + refopt.step() + assert all(p.grad is None for p in teacher.parameters()) + for name, p in full(model).items(): + torch.testing.assert_close(p, reference.state_dict()[name], rtol=2e-5, atol=2e-6, msg=name) + if rank == 0: + report = { + "state": "passed", + "world_size": dist.get_world_size(), + "updates": 8, + "max_forward_abs_diff": max_output, + "max_gradient_abs_diff_rank0": max_grad, + "teacher_frozen": True, + "model": "random tiny Qwen-Image 2.1", + } + (cli.output / "verification.json").write_text(json.dumps(report, indent=2)) + print(json.dumps(report), flush=True) + dist.destroy_process_group() + + +if __name__ == "__main__": + main() diff --git a/tests/fast-gpu/backends/fsdp_utils/test_pdd.py b/tests/fast-gpu/backends/fsdp_utils/test_pdd.py new file mode 100644 index 000000000..bb92fd571 --- /dev/null +++ b/tests/fast-gpu/backends/fsdp_utils/test_pdd.py @@ -0,0 +1,43 @@ +"""PDD FSDP parity through the generic loader hooks.""" + +from tests.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=90, suite="stage-b-5-gpu-h200", labels=["fsdp"]) + +import json +import os +import subprocess +import sys +from pathlib import Path + +import pytest +import torch + + +@pytest.mark.parametrize("world_size", [1, 2]) +def test_pdd_fsdp_parity(tmp_path, world_size): + if torch.cuda.device_count() < world_size: + pytest.skip(f"Requires {world_size} CUDA devices") + result = subprocess.run( + [ + sys.executable, + "-m", + "torch.distributed.run", + "--standalone", + f"--nproc-per-node={world_size}", + str(Path(__file__).with_name("_pdd_worker.py")), + "--output", + str(tmp_path), + ], + env={**os.environ, "PYTHONUNBUFFERED": "1"}, + capture_output=True, + text=True, + timeout=300, + ) + assert result.returncode == 0, result.stdout + result.stderr + report = json.loads((tmp_path / "verification.json").read_text()) + assert report["state"] == "passed" and report["world_size"] == world_size + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v"])) 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..e894b7c52 --- /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"]["visual"], second["pdd_trajectory"]["visual"]) + with torch.no_grad(): + for block in expand_train_pairs(ctx, [second]): + prepared = prepare_pdd_batch(ctx, [block], microbatch_id=0, optim_step_idx=0) + x, start = prepared.latents["visual"], block["pdd_start"] + heads = predict(prepared)["visual"].reshape(*x.shape[:-1], 32, x.shape[-1]).permute(2, 0, 1, 3) + for end in range(start + 1, start + 5): + following = block_update(x, heads, prepared.extras["grids"]["visual"], start, end) + expected = second["pdd_trajectory"]["visual"][end].cuda().unsqueeze(0) + # Mismatched BF16 timestep rounding alone gave 1.5-3% on some blocks. + relative = (following - expected).abs().mean() / (expected - x).abs().mean() + assert relative < 5e-3, (start, end, float(relative)) + 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_miles_pdd_integration.py b/tests/fast/distillation/test_miles_pdd_integration.py new file mode 100644 index 000000000..86b435b36 --- /dev/null +++ b/tests/fast/distillation/test_miles_pdd_integration.py @@ -0,0 +1,342 @@ +"""Trainer side: eight block updates from rollout states match an independent optimizer loop. + +The test plays the actor: it runs the prepare hook's teacher solver with its own teacher forward, +then hands the result to the formula as ``teacher_pred``. +""" + +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.distillation import integration +from miles.distillation.integration import expand_train_pairs, expand_trajectories, install_student +from miles.distillation.pdd import ParallelLinear, pdd_loss + + +@pytest.fixture(autouse=True) +def linear_grid(monkeypatch): + monkeypatch.setattr(integration, "make_grid", lambda *args: torch.linspace(1, 0, 33)) + + +class Model(nn.Module): + def __init__(self): + super().__init__() + self.config = SimpleNamespace(in_channels=2, patch_size=1) + self.base = nn.Linear(2, 2) + self.head = ParallelLinear(nn.Linear(2, 2), 32) + + def forward(self, x, sigma): + return self.head(self.base(x) + sigma.reshape(-1, 1, 1)) + + +class Config: + def compute_noise_pred(self, *, model, latents_input, timesteps_input, **kw): + return {"visual": model(latents_input["visual"].float(), timesteps_input["visual"])} + + def prepare_cond_kwargs(self, cond, device): + return cond + + +class Teacher(nn.Module): + def __init__(self): + super().__init__() + self.scale = nn.Parameter(torch.tensor(0.3), requires_grad=False) + self.calls = [] + + def forward(self, x, sigma): + self.calls.append((x.detach().clone(), sigma.detach().clone())) + return self.scale * x + sigma.reshape(-1, 1, 1) + + +class Metrics: + def emit_mean(self, *args, **kwargs): + pass + + +def context(student, rollout=0): + return DiffusionLossContext( + models={"transformer": student}, + train_pipeline_config=Config(), + sde_backend=None, + device=torch.device("cpu"), + forward_dtype=torch.float32, + args=SimpleNamespace( + diffusion_model_family="qwen_image21", + hf_checkpoint="unused", + pdd_num_intervals=32, + pdd_block_size=4, + diffusion_height=32, + seed=42, + ), + rollout_id=rollout, + ) + + +def teacher_target(teacher, prepared): + """What the actor does with ``prepared.teacher_solver``, without grad.""" + with torch.no_grad(): + return prepared.teacher_solver( + lambda latents, timesteps: {"visual": teacher(latents["visual"], timesteps["visual"])} + ) + + +def raw_forward(model, prepared): + pred = model(prepared.latents["visual"], prepared.timesteps_for_model["visual"]) + return {"visual": pred.permute(1, 2, 0, 3).flatten(2)} + + +def rollout_pair(index): + return dict( + sample_index=index, + pdd_trajectory={"visual": torch.randn(33, 4, 2)}, + denoising_env=SimpleNamespace(pos_cond_kwargs={}), + ) + + +def test_eight_block_updates_from_rollout_states_match_reference(): + torch.manual_seed(12) + student = Model() + reference = copy.deepcopy(student) + teacher = Teacher() + ctx = context(student) + opt = torch.optim.AdamW(student.parameters(), lr=1e-3, weight_decay=0) + refopt = torch.optim.AdamW(reference.parameters(), lr=1e-3, weight_decay=0) + pairs = [rollout_pair(i) for i in (2, 9)] + expanded = expand_train_pairs(ctx, 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) + start, k, grids = (prepared.extras[v] for v in ("start", "selected", "grids")) + x = prepared.latents["visual"] + torch.testing.assert_close(x[0], pair["pdd_trajectory"]["visual"][4 * step], rtol=0, atol=0) + assert start == 4 * step and not x.requires_grad + predictions = reference(x, prepared.timesteps_for_model["visual"]) + # The teacher starts from the rollout's state at the sampled interval. + x_selected = pair["pdd_trajectory"]["visual"][k].unsqueeze(0) + expected = pdd_loss( + predictions, + x, + grids["visual"], + start, + k, + lambda state, sigma: teacher(state, sigma.expand(1)), + x_selected=x_selected, + ) + calls = len(teacher.calls) + target = teacher_target(teacher, prepared) + torch.testing.assert_close(teacher.calls[calls][0], x_selected, rtol=0, atol=0) + loss = pdd_loss_formula( + ctx, + [pair], + prepared, + new_pred=raw_forward(student, prepared), + old_pred=None, + ref_pred=None, + teacher_pred=target, + metrics=Metrics(), + optim_step_idx=0, + train_output_inputs=[], + ) + torch.testing.assert_close(loss, expected.sum(), rtol=0, atol=0) + (loss / 2).backward() + (expected.sum() / 2).backward() + for a, b in zip(student.parameters(), reference.parameters(), strict=True): + torch.testing.assert_close(a.grad, b.grad, rtol=0, atol=0) + 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(): + student = Model() + pair = dict(rollout_pair(99), pdd_start=0) + chosen = prepare_pdd_batch(context(student, 7), [pair], microbatch_id=0, optim_step_idx=0).extras["selected"] + torch.randn(500) # unrelated process RNG must not affect a resumed rollout + assert ( + prepare_pdd_batch(context(student, 7), [pair], microbatch_id=0, optim_step_idx=0).extras["selected"] == chosen + ) + choices = { + prepare_pdd_batch(context(student, r), [pair], microbatch_id=0, optim_step_idx=0).extras["selected"] + for r in range(32) + } + assert choices == {0, 1, 2, 3} + + +def test_heads_installed_on_meta_before_sharding(): + with torch.device("meta"): + model = nn.Module() + model.proj_out = nn.Linear(4, 2) + model.config = SimpleNamespace(patch_size=1, in_channels=2) + install_student(model, SimpleNamespace(diffusion_model_family="qwen_image21", pdd_num_intervals=32)) + assert all(p.is_meta for p in model.parameters()) + assert model.proj_out.parallel.weight.shape == (32, 2, 4) + + +def test_dp_split_precedes_trajectory_expansion(): + from miles.utils.train_data_utils import TrainDataDPSplitter + + pairs = [{"sample_index": i} for i in range(8)] + shards = TrainDataDPSplitter().split_by_dp({"train_data": pairs}, 2) + for shard in shards: + expanded = expand_trajectories(shard["train_data"], intervals=32, block_size=4) + for start in range(8): + window = expanded[start * 4 : (start + 1) * 4] + assert [p["sample_index"] for p in window] == [p["sample_index"] for p in shard["train_data"]] + assert all(p["pdd_start"] == start * 4 for p in window) + with pytest.raises(ValueError, match="distinct lane"): + expand_trajectories([pairs[0], pairs[0]], intervals=32, block_size=4) + + +def valid_args(): + return SimpleNamespace( + diffusion_model_family="qwen_image21", + diffusion_task="t2i", + train_only=False, + 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, + micro_batch_size_sample=None, + sequence_parallel_size=1, + use_lora=True, + colocate=True, + lora_ipc_weight_sync=True, + sglang_lora_merge_mode="dynamic", + use_ema=False, + ref_load=None, + ref_mode="none", + teacher_lora_adapter_paths=None, + lora_adapter_paths=None, + diffusion_recompute_old_log_prob=False, + diffusion_kl_beta=0, + 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", + teacher_load=None, + 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", + diffusion_step_strategy_path=None, + custom_generate_function_path=None, + group_rm=False, + rollout_patch_group=None, + rollout_function_path="miles.rollout.sglang_rollout.generate_rollout", + custom_convert_samples_to_train_data_path=None, + custom_rm_path=None, + custom_train_model_transform_path=None, + fsdp_param_dtype=None, + rollout_return_full_trajectory=False, + num_steps_per_rollout=None, + global_batch_size=None, + rollout_batch_size=8, + ) + + +def configure(args, **overrides): + """set_default_diffusion_args -> user overrides stand -> miles_validate_args, as in parse_args.""" + from miles.distillation.integration import set_pdd_defaults, validate_pdd_args + + 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) + + +def test_defaults_select_sglang_rollout_and_eight_updates(): + args = valid_args() + configure(args) + assert args.global_batch_size == 8 and args.num_steps_per_rollout == 8 + assert args.teacher_load == args.hf_checkpoint + assert args.rollout_function_path == "miles.rollout.sglang_diffusion_rollout.generate_rollout" + assert args.rollout_patch_groups == ["pdd_qwen_image21"] and args.rollout_return_full_trajectory + from miles.backends.fsdp_utils.loss_hub import LOSS_HOOKS + + hooks = LOSS_HOOKS[("pdd", "actor")] + assert (hooks.prepare, hooks.formula, hooks.train_input) == ( + prepare_pdd_batch, + pdd_loss_formula, + expand_train_pairs, + ) + assert args.custom_train_model_transform_path.endswith("integration.install_student") + assert args.fsdp_param_dtype == "fp32" + + +@pytest.mark.parametrize( + "name,value", + [ + ("sequence_parallel_size", 2), + ("use_lora", False), + ("lora_ipc_weight_sync", False), + ("sglang_lora_merge_mode", "merge"), + ("train_only", True), + ("pdd_block_size", 8), + ("diffusion_guidance_scale", 4), + ("custom_rm_path", "miles.rollout.rm_hub.other"), + ("teacher_load", "other-model"), + ("global_batch_size", 1), + ("num_steps_per_rollout", 1), + ("diffusion_height", 512), + ("diffusion_num_steps", 40), + ("diffusion_noise_level", 0.1), + ("rollout_num_gpus_per_engine", 2), + ("rollout_microgroup_size", 2), + ("sglang_dit_precision", "bf16"), + ("rollout_patch_group", "qwen_image21"), + ], +) +def test_unvalidated_modes_fail_before_gpu_load(name, value): + with pytest.raises(ValueError): + configure(valid_args(), **{name: value}) + + +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) + + # The loader's order: LoRA first, then the model-transform hook on the unwrapped model. + model = get_peft_model(Tiny(), LoraConfig(r=2, lora_alpha=2, target_modules=["to_q"])) + install_student( + model.get_base_model(), SimpleNamespace(diffusion_model_family="qwen_image21", pdd_num_intervals=32) + ) + 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 diff --git a/tests/fast/distillation/test_pdd.py b/tests/fast/distillation/test_pdd.py new file mode 100644 index 000000000..9b8eeb8ca --- /dev/null +++ b/tests/fast/distillation/test_pdd.py @@ -0,0 +1,86 @@ +from tests.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=5, suite="stage-a-cpu", labels=[]) + +import pytest +import torch +from torch import nn + +from miles.distillation.pdd import ParallelLinear, block_update, pdd_loss, teacher_mean_velocity + + +@pytest.mark.parametrize("solver", ["euler", "midpoint"]) +@pytest.mark.parametrize("descending", [False, True]) +def test_target_uses_detached_student_state_and_signed_step(solver, descending): + grid = torch.tensor([0.0, 0.2, 0.7, 1.0]) + if descending: + grid = grid.flip(0) + x = torch.tensor([[1.0, 2.0]], requires_grad=True) + predictions = torch.tensor([[[2.0, 3.0]], [[4.0, 5.0]], [[6.0, 7.0]]], requires_grad=True) + teacher_weight = nn.Parameter(torch.tensor(0.5)) + seen = [] + + def teacher(state, time): + seen.append((state.detach().clone(), torch.is_grad_enabled())) + return teacher_weight * state + time + + loss = pdd_loss(predictions, x, grid, 0, 1, teacher, solver=solver).mean() + expected_state = x.detach() + (grid[1] - grid[0]) * predictions[0].detach() + velocity = 0.5 * expected_state + grid[1] + if solver == "midpoint": + h = grid[2] - grid[1] + velocity = 0.5 * (expected_state + h * 0.5 * velocity) + grid[1] + h * 0.5 + torch.testing.assert_close(seen[0][0], expected_state) + torch.testing.assert_close(loss, (predictions[1] - velocity).square().mean()) + assert len(seen) == (1 if solver == "euler" else 2) + assert all(not enabled for _, enabled in seen) + loss.backward() + assert x.grad is None and teacher_weight.grad is None + assert predictions.grad[0].count_nonzero() == 0 + assert predictions.grad[1].count_nonzero() > 0 + assert predictions.grad[2].count_nonzero() == 0 + + +def test_head_initialization_and_shared_backbone_gradient(): + source = nn.Linear(3, 2) + head = ParallelLinear(source, 4) + hidden = torch.randn(5, 3, requires_grad=True) + outputs = head(hidden) + for output in outputs: + torch.testing.assert_close(output, source(hidden)) + outputs[2].square().mean().backward() + assert hidden.grad.abs().sum() > 0 + assert head.weight.grad[2].abs().sum() > 0 + assert head.weight.grad[[0, 1, 3]].count_nonzero() == 0 + + +@pytest.mark.parametrize("descending", [False, True]) +@pytest.mark.parametrize("block_size", [1, 2, 4, 8]) +def test_oracle_mean_velocities_follow_exact_linear_ode_across_block_sizes(descending, block_size): + """Independent analytic oracle: dx/dt = a*x on a nonuniform grid.""" + 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 = torch.tensor(-0.7, dtype=torch.float64) + initial = torch.tensor([[1.3, -2.1]], dtype=torch.float64) + + def oracle(state, time): + # Each head is the analytic integral from its own interval, relative to + # this call's block-start state. No sampler helpers construct the oracle. + left = torch.exp(a * (grid[:-1] - time)) + right = torch.exp(a * (grid[1:] - time)) + means = (right - left) / (grid[1:] - grid[:-1]) + return means[:, None, None] * state + + actual = initial + for start in range(0, 8, block_size): + actual = block_update(actual, oracle(actual, grid[start]), grid, start, start + block_size) + expected = initial * torch.exp(a * (grid[-1] - grid[0])) + torch.testing.assert_close(actual, expected, rtol=1e-12, atol=1e-12) + + +def test_invalid_inputs_fail_instead_of_broadcasting(): + with pytest.raises(ValueError): + pdd_loss(torch.zeros(3, 2, 1), torch.zeros(2, 1), torch.tensor([0.0, 0.5, 0.4, 1.0]), 0, 1, None) + with pytest.raises(ValueError): + teacher_mean_velocity(lambda x, t: x[:, :1], torch.zeros(2, 3), torch.tensor(0.0), torch.tensor(0.1)) diff --git a/tests/fast/distillation/test_pdd_rollout.py b/tests/fast/distillation/test_pdd_rollout.py new file mode 100644 index 000000000..33e82b7e5 --- /dev/null +++ b/tests/fast/distillation/test_pdd_rollout.py @@ -0,0 +1,83 @@ +"""Rollout side: engine heads, trajectory conversion, timestep matching and resume signature.""" + +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 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_trajectories +from miles.distillation.pdd import block_update +from miles.rollout import pdd_rollout + + +def test_engine_interval_steps_match_pdd_and_see_live_weight_updates(): + """The engine's 32 Euler steps on one cached forward per block reproduce every interval start.""" + torch.manual_seed(8) + projection = PDDProjection(torch.nn.Linear(3, 2)) + grid = torch.linspace(1, 0, 33).square() + hidden, state = torch.randn(1, 5, 3), torch.randn(1, 5, 2) + x = state + for interval in range(32): + start = interval - interval % 4 + if interval == start: + head = projection(hidden) + torch.testing.assert_close(head, 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) + before = projection(hidden).clone() + with torch.no_grad(): + projection.parallel.weight.add_(0.5) + assert not torch.equal(before, projection(hidden)) + assert set(projection.state_dict()) == {"parallel.weight", "parallel.bias"} + + +def test_converter_validates_grid_and_complete_trajectory(monkeypatch): + grid = torch.linspace(1, 0, 33) + monkeypatch.setattr(integration, "make_grid", lambda *args: 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( + diffusion_model_family="qwen_image21", hf_checkpoint="unused", diffusion_height=32, pdd_num_intervals=32 + ) + pair = pdd_rollout.convert_samples_to_train_data(args, [sample])["train_data"][0] + torch.testing.assert_close(pair["pdd_trajectory"]["visual"], sample.dit_trajectory.latents) + blocks = expand_trajectories([pair], intervals=32, block_size=4) + assert [block["pdd_start"] for block in blocks] == list(range(0, 32, 4)) + for field, value in [ + ("sigmas", grid[::4]), + ("sigmas", grid + 0.01), + ("latents", torch.randn(9, 4, 2)), + ("latents", torch.full((33, 4, 2), float("nan"))), + ("latent_step_indices", torch.arange(1, 34)), + ]: + bad = copy.deepcopy(sample) + setattr(bad.dit_trajectory, field, value) + with pytest.raises(ValueError): + pdd_rollout.convert_samples_to_train_data(args, [bad]) + + +def test_engine_timesteps_reproduce_trainer_bf16_sigma(): + # 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() + embedded = embedded_sigmas(engine_timesteps(sigmas)) + fixed = embedded != sigmas.bfloat16().float() + assert naive.float().mean() > 0.2 and fixed.float().mean() < 0.05 and not (fixed & ~naive).any() + # Unreachable sigmas fall back to the nearest embeddable value, which the trainer adopts. + assert (embedded - sigmas).abs().max() < 8e-3 From cf18d745721962db415e91dea35a61bae133167f Mon Sep 17 00:00:00 2001 From: niehen6174 <1639206518@qq.com> Date: Fri, 13 Nov 2026 19:48:10 +0800 Subject: [PATCH 2/3] refactor(pdd): drop the multi-stream family registry; share Qwen constants with the rollout patch This PR ships Qwen-Image 2.1 only, so the per-family/per-stream abstraction had a single user: - Remove PDDFamily/PDD_FAMILIES. Qwen's grid and student time input become plain helpers (pdd_grid, model_time) and its scope is checked directly in validate_pdd_args. - Rollout trajectories are one [33, S, C] tensor instead of a dict of streams; the loss hook and teacher_mean_velocity work on a single latent tensor. This also removes per-stream metric names that were not in the metrics SCHEMA. - The SGLang patch reads the interval count, block size, resolution and token count from the same constants the argument validation uses. --- docs/developer/pdd.md | 20 ++-- miles/backends/fsdp_utils/loss_hub/pdd.py | 86 +++++-------- .../monkey_patches/patch_pdd_qwen_image21.py | 27 +++-- miles/distillation/integration.py | 113 +++++------------- miles/distillation/pdd.py | 27 +---- miles/rollout/pdd_rollout.py | 13 +- .../backends/fsdp_utils/_pdd_worker.py | 2 +- .../test_pdd_sglang_loop.py | 6 +- .../test_miles_pdd_integration.py | 10 +- tests/fast/distillation/test_pdd_rollout.py | 2 +- 10 files changed, 114 insertions(+), 192 deletions(-) diff --git a/docs/developer/pdd.md b/docs/developer/pdd.md index 439a26d6e..1b0aeaa9c 100644 --- a/docs/developer/pdd.md +++ b/docs/developer/pdd.md @@ -9,7 +9,7 @@ checkpoints. ## Supported configuration -- 32 output heads per latent stream, four intervals per block: eight student +- 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. @@ -22,38 +22,36 @@ checkpoints. - No EMA, RL log probabilities, reference-policy loss, dynamic batching, Cache-DiT or compiled/graph execution. -| Family | Task | Streams | Grid | Engine weights | FSDP all-gather | -|---|---|---|---|---|---| -| `qwen_image21` | t2i, 1024 × 1024 | visual | the scheduler's shifted grid | FP32 | FP32, BF16 autocast | +- 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 per stream) for eight DiT forwards. + 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, one joint teacher call - per midpoint stage for all streams; the loss regresses the selected head of every - stream on it and steps once. Block j's states were produced j updates before the + 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 layers are replicated into heads after LoRA is applied and before +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. What differs per model family lives in `PDD_FAMILIES`: +branches: | Hook | PDD default | |---|---| -| `--custom-train-model-transform-path` | `install_student`: each stream's output layer as 32 heads, after LoRA | +| `--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` | diff --git a/miles/backends/fsdp_utils/loss_hub/pdd.py b/miles/backends/fsdp_utils/loss_hub/pdd.py index 8fda0acf9..cbd8688be 100644 --- a/miles/backends/fsdp_utils/loss_hub/pdd.py +++ b/miles/backends/fsdp_utils/loss_hub/pdd.py @@ -1,40 +1,33 @@ """PDD prepare/loss hooks. The FSDP actor owns every DiT forward: the student's, and the teacher's midpoint solve from the rollout's interval state, requested by prepare. - -Every latent stream of the family moves on its own grid; one -sampled interval and one joint teacher call cover all streams. """ import torch -from miles.distillation.integration import pdd_family +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 - family = pdd_family(args) start, lane = pair["pdd_start"], pair["sample_index"] if start not in range(0, args.pdd_num_intervals, args.pdd_block_size): raise ValueError("Invalid PDD rollout block index") - grids = {stream: grid.to(ctx.device) for stream, grid in family.grids(args).items()} + 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"] - if set(trajectory) != set(family.heads): - raise ValueError(f"PDD rollout streams {sorted(trajectory)} differ from {sorted(family.heads)}") - states, x_selected = ( - {stream: trajectory[stream][i].to(ctx.device).unsqueeze(0).float() for stream in family.heads} - for i in (start, selected) - ) - if not all(torch.isfinite(state).all() for state in states.values()): + 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. @@ -46,27 +39,18 @@ def prepare_pdd_batch(ctx, batch, *, microbatch_id, optim_step_idx, pad_to_len=N ) for k, v in condition.items() } - condition.update(family.cond_extras) - - def time(time_fn, index): - return {stream: time_fn(args, stream, grid[index].reshape(1)).to(ctx.device) for stream, grid in grids.items()} def solve(forward): def teacher(x, sigma): - timesteps = { - stream: family.teacher_time(args, stream, value.reshape(1)) for stream, value in sigma.items() - } - pred = forward(x, timesteps) - return {stream: pred[stream].float() for stream in x} + return forward({STREAM: x}, {STREAM: sigma.reshape(1)})[STREAM].float() - sigma = {stream: grid[selected] for stream, grid in grids.items()} - delta = {stream: grid.diff()[selected] for stream, grid in grids.items()} - return teacher_mean_velocity(teacher, x_selected, sigma, delta, solver="midpoint") + target = teacher_mean_velocity(teacher, x_selected, grid[selected], grid.diff()[selected], solver="midpoint") + return {STREAM: target} return PreparedBatch( - latents=states, - timesteps={stream: grid[start].reshape(1) for stream, grid in grids.items()}, - timesteps_for_model=time(family.model_time, start), + 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, @@ -77,7 +61,7 @@ def teacher(x, sigma): neg_cond=None, joint_cond=None, advantage=torch.ones(1, device=ctx.device), - extras={"start": start, "selected": selected, "lane": lane, "grids": grids}, + extras={"start": start, "selected": selected, "lane": lane, "grid": grid}, teacher_guidance_scale=1.0, teacher_solver=solve, ) @@ -103,31 +87,25 @@ def pdd_loss_formula( if teacher_pred is None: raise ValueError("PDD needs the teacher target its prepare hook requested") n = ctx.args.pdd_num_intervals - start, selected, grids = (prepared.extras[k] for k in ("start", "selected", "grids")) + start, selected, grid = (prepared.extras[k] for k in ("start", "selected", "grid")) end = start + ctx.args.pdd_block_size - per_sample_loss = 0 - for stream, x in prepared.latents.items(): - raw = new_pred[stream] - if raw.shape != (*x.shape[:-1], n * x.shape[-1]): - raise ValueError(f"PDD student {stream} output shape does not match the parallel heads") - predictions = raw.reshape(*x.shape[:-1], n, x.shape[-1]).permute(2, 0, 1, 3) - stream_loss = interval_loss(predictions, selected, teacher_pred[stream]) - if not torch.isfinite(stream_loss).all(): - raise FloatingPointError(f"nonfinite PDD {stream} loss") - per_sample_loss = per_sample_loss + stream_loss - with torch.no_grad(): - following = block_update(x, predictions, grids[stream], start, end).detach() - if not torch.isfinite(following).all(): - raise FloatingPointError(f"nonfinite PDD {stream} trajectory") - # Trainer vs. engine next state; later blocks also include rollout staleness. - expected = batch[0]["pdd_trajectory"][stream][end].to(ctx.device).unsqueeze(0).float() - error = (following - expected).abs() - prefix = "pdd" if stream == "visual" else f"pdd_{stream}" - metrics.emit_mean(f"{prefix}_next_latent_mae", total=error.sum(), count=error.numel()) - relative = error.mean() / (expected - x).abs().mean().clamp_min(1e-6) - metrics.emit_mean(f"{prefix}_update_relative_error", total=relative, count=1) - if len(prepared.latents) > 1: - metrics.emit_mean(f"pdd_{stream}_loss", total=stream_loss.sum(), count=len(batch)) + 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(): - metrics.emit_mean("loss", total=per_sample_loss.sum().detach(), count=len(batch)) + 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/sglang_diffusion_utils/monkey_patches/patch_pdd_qwen_image21.py b/miles/backends/sglang_diffusion_utils/monkey_patches/patch_pdd_qwen_image21.py index 4f0aaaaef..498b40abe 100644 --- 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 @@ -1,4 +1,4 @@ -"""Experimental head-only PDD rollout. Keep the native DiT and rollout scheduler. +"""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 @@ -10,14 +10,21 @@ import torch from torch import nn -from miles.distillation.integration import engine_timesteps, make_grid +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, 32) + self.parallel = ParallelLinear(source, NUM_INTERVALS) self.interval = None self.block = None @@ -53,15 +60,19 @@ def post_load(self): 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) != (1024, 1024, 8): - raise ValueError("PDD requires 1024x1024 and 8 steps") + 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, 32, 4096, batch.timesteps.device) + 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 = 32 + batch.num_inference_steps = NUM_INTERVALS return batch def prepare(self, batch, server_args): @@ -81,7 +92,7 @@ def prepare(self, batch, server_args): def predict(self, current_model, *args, **kwargs): head = current_model.proj_out - if head.interval % 4 == 0: + if head.interval % BLOCK_SIZE == 0: original_predict(self, current_model, *args, **kwargs) return head.block[head.interval] diff --git a/miles/distillation/integration.py b/miles/distillation/integration.py index dcfdc4708..7a32f05f7 100644 --- a/miles/distillation/integration.py +++ b/miles/distillation/integration.py @@ -2,15 +2,10 @@ 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``. What -differs per model family (latent streams, sigma grids, time inputs, rollout patch) -lives in ``PDD_FAMILIES``. +generic Miles hooks; nothing in the trainer branches on ``--loss-type pdd``. """ import functools -from collections.abc import Callable -from dataclasses import dataclass, field -from typing import Any import torch @@ -75,70 +70,29 @@ def forward(self, hidden): return self.parallel(hidden).permute(1, 2, 0, 3).flatten(2) -@dataclass(frozen=True) -class PDDFamily: - """What PDD needs from one model family, looked up by ``--diffusion-model-family``. +# 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" - ``heads`` maps each latent stream to the Diffusers transformer's output layer that becomes N heads; - ``grids(args)`` gives each stream's (N+1)-point sigma grid; ``model_time`` / ``teacher_time`` turn a grid - sigma into the student's and the teacher's ``timesteps_for_model``; ``split_states`` cuts the rollout's - per-interval states into streams; ``validate`` checks the family's rollout settings. - """ - task: str - heads: dict[str, str] - patch_group: str - engine_precision: str - # None keeps the family's FSDP plan (e.g. FP32 heads over a BF16 all-gather). - fsdp_param_dtype: str | None - grids: Callable[[Any], dict[str, torch.Tensor]] - model_time: Callable[[Any, str, torch.Tensor], torch.Tensor] - teacher_time: Callable[[Any, str, torch.Tensor], torch.Tensor] - split_states: Callable[[torch.Tensor, Any], dict[str, torch.Tensor]] - validate: Callable[[Any], None] - cond_extras: dict[str, Any] = field(default_factory=dict) - - -def _qwen_validate(args): - if args.diffusion_height != 1024 or args.diffusion_width != 1024: - raise ValueError("PDD requires 1024 x 1024 for Qwen-Image 2.1") - - -PDD_FAMILIES = { - "qwen_image21": PDDFamily( - task="t2i", - heads={"visual": "proj_out"}, - patch_group="pdd_qwen_image21", - engine_precision="fp32", - # Gathered student weights stay FP32 (head biases, norms); autocast handles matmuls. - fsdp_param_dtype="fp32", - grids=lambda args: { - "visual": make_grid(args.hf_checkpoint, args.pdd_num_intervals, (args.diffusion_height // 16) ** 2) - }, - # The student sees the time value SGLang embedded; the grid dynamics stay unchanged. - model_time=lambda args, stream, sigma: embedded_sigmas(engine_timesteps(sigma)), - teacher_time=lambda args, stream, sigma: sigma, - split_states=lambda states, env: {"visual": states}, - validate=_qwen_validate, - ), -} +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 pdd_family(args): - try: - return PDD_FAMILIES[args.diffusion_model_family] - except KeyError: - raise ValueError(f"PDD supports --diffusion-model-family {sorted(PDD_FAMILIES)}") from None +def 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: each stream's output layer becomes N heads, trained in - full beside the backbone's LoRA adapters.""" - for attr in pdd_family(args).heads.values(): - layer = getattr(model, attr) - if not isinstance(layer, torch.nn.Linear): - raise ValueError(f"PDD needs an unmodified {attr} output layer") - setattr(model, attr, TokenParallelProjection(layer, args.pdd_num_intervals)) + """``--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): @@ -169,12 +123,11 @@ def set_pdd_defaults(args): setattr(args, key, value) if args.rollout_function_path == "miles.rollout.sglang_rollout.generate_rollout": args.rollout_function_path = _DIFFUSION_ROLLOUT - family = PDD_FAMILIES.get(args.diffusion_model_family) - if family is not None: - if args.rollout_patch_group is None: - args.rollout_patch_group = family.patch_group - if args.fsdp_param_dtype is None: - args.fsdp_param_dtype = family.fsdp_param_dtype + if args.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 @@ -187,15 +140,15 @@ def set_pdd_defaults(args): def validate_pdd_args(args): """Narrow, validated integration; unsupported modes fail before loading GPUs.""" - family = pdd_family(args) - if args.diffusion_task != family.task: - raise ValueError(f"PDD supports {args.diffusion_model_family} {family.task} only") - family.validate(args) + if args.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) != (32, 4): + 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") @@ -233,14 +186,14 @@ def validate_pdd_args(args): raise ValueError("PDD requires --diffusion-sde-type ode --diffusion-noise-level 0") if args.rollout_num_gpus_per_engine != 1 or args.rollout_microgroup_size != 1: raise ValueError("PDD requires one GPU per engine and rollout microgroup size 1") - if args.sglang_dit_precision != family.engine_precision: - raise ValueError(f"PDD requires --sglang-dit-precision {family.engine_precision}") - if args.fsdp_param_dtype != family.fsdp_param_dtype: - raise ValueError(f"PDD requires --fsdp-param-dtype {family.fsdp_param_dtype}") + if args.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 != [family.patch_group]: - raise ValueError(f"PDD requires only the {family.patch_group} rollout patch group") + 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}") diff --git a/miles/distillation/pdd.py b/miles/distillation/pdd.py index 6c1ac3afc..7e8f0fc3a 100644 --- a/miles/distillation/pdd.py +++ b/miles/distillation/pdd.py @@ -42,38 +42,23 @@ def forward(self, hidden: torch.Tensor) -> torch.Tensor: return result -def _each(fn, *trees): - """Apply ``fn`` leafwise over tensors or same-keyed dicts of tensors (one entry per latent stream).""" - if isinstance(trees[0], dict): - return {key: fn(*(tree[key] for tree in trees)) for key in trees[0]} - return fn(*trees) - - @torch.no_grad() -def teacher_mean_velocity(teacher: Callable, x, time, delta, solver: str = "midpoint"): - """Teacher closure includes conditioning/CFG; never build a teacher gradient graph. - - ``x``, ``time`` and ``delta`` are tensors, or dicts keyed by latent stream for a joint - model whose streams move on their own grids in one teacher call. - """ +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) - pairs = [(velocity[k], state[k]) for k in state] if isinstance(state, dict) else [(velocity, state)] - if any(v.shape != s.shape for v, s in pairs): + if velocity.shape != state.shape: raise ValueError("teacher output must match the latent shape exactly") return velocity - x = _each(torch.Tensor.detach, x) + x = x.detach() velocity = call(x, time) if solver == "midpoint": - velocity = call( - _each(lambda s, d, v: s + 0.5 * d * v, x, delta, velocity), - _each(lambda t, d: t + 0.5 * d, time, delta), - ) - return _each(torch.Tensor.detach, velocity) + 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: diff --git a/miles/rollout/pdd_rollout.py b/miles/rollout/pdd_rollout.py index 30b1c80ab..9bdd4e018 100644 --- a/miles/rollout/pdd_rollout.py +++ b/miles/rollout/pdd_rollout.py @@ -1,7 +1,6 @@ """PDD rollout hooks: validate SGLang trajectories for the block-ordered updates. -SGLang returns the start state of all 32 intervals plus the endpoint, per latent -stream (the family's ``split_states`` cuts a packed trajectory into streams). The actor +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 @@ -10,7 +9,7 @@ import torch -from miles.distillation.integration import pdd_family +from miles.distillation.integration import pdd_grid async def no_reward(args, samples, **kwargs): @@ -20,15 +19,14 @@ async def no_reward(args, samples, **kwargs): def convert_samples_to_train_data(args, samples): - family = pdd_family(args) - grids = family.grids(args) + 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(), grids["visual"]): + 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. @@ -41,8 +39,7 @@ def convert_samples_to_train_data(args, samples): raise ValueError(f"PDD expects per-sample packed latent tokens [{states_count}, S, C]") if not torch.isfinite(states).all(): raise ValueError("PDD rollout contains nonfinite states") - streams = family.split_states(states, env) - pairs.append(dict(sample_index=sample.index, pdd_trajectory=streams, denoising_env=env)) + 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/tests/fast-gpu/backends/fsdp_utils/_pdd_worker.py b/tests/fast-gpu/backends/fsdp_utils/_pdd_worker.py index 87ecd596d..33212fbf4 100644 --- a/tests/fast-gpu/backends/fsdp_utils/_pdd_worker.py +++ b/tests/fast-gpu/backends/fsdp_utils/_pdd_worker.py @@ -126,7 +126,7 @@ def main(): pair = { "sample_index": rank, "pdd_start": start, - "pdd_trajectory": {"visual": trajectory}, + "pdd_trajectory": trajectory, "denoising_env": env, } prepared = prepare_pdd_batch(ctx, [pair], microbatch_id=0, optim_step_idx=0) diff --git a/tests/fast-gpu/backends/sglang_diffusion_utils/test_pdd_sglang_loop.py b/tests/fast-gpu/backends/sglang_diffusion_utils/test_pdd_sglang_loop.py index e894b7c52..6fc953c9a 100644 --- a/tests/fast-gpu/backends/sglang_diffusion_utils/test_pdd_sglang_loop.py +++ b/tests/fast-gpu/backends/sglang_diffusion_utils/test_pdd_sglang_loop.py @@ -263,15 +263,15 @@ def forward(latents, timesteps): # The trained heads now drive the engine; every interval state must match the trainer's heads. second = rollout() - assert not torch.equal(first["pdd_trajectory"]["visual"], second["pdd_trajectory"]["visual"]) + 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["grids"]["visual"], start, end) - expected = second["pdd_trajectory"]["visual"][end].cuda().unsqueeze(0) + 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)) diff --git a/tests/fast/distillation/test_miles_pdd_integration.py b/tests/fast/distillation/test_miles_pdd_integration.py index 86b435b36..6aacad70b 100644 --- a/tests/fast/distillation/test_miles_pdd_integration.py +++ b/tests/fast/distillation/test_miles_pdd_integration.py @@ -97,7 +97,7 @@ def raw_forward(model, prepared): def rollout_pair(index): return dict( sample_index=index, - pdd_trajectory={"visual": torch.randn(33, 4, 2)}, + pdd_trajectory=torch.randn(33, 4, 2), denoising_env=SimpleNamespace(pos_cond_kwargs={}), ) @@ -117,17 +117,17 @@ def test_eight_block_updates_from_rollout_states_match_reference(): 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) - start, k, grids = (prepared.extras[v] for v in ("start", "selected", "grids")) + start, k, grid = (prepared.extras[v] for v in ("start", "selected", "grid")) x = prepared.latents["visual"] - torch.testing.assert_close(x[0], pair["pdd_trajectory"]["visual"][4 * step], rtol=0, atol=0) + torch.testing.assert_close(x[0], pair["pdd_trajectory"][4 * step], rtol=0, atol=0) assert start == 4 * step and not x.requires_grad predictions = reference(x, prepared.timesteps_for_model["visual"]) # The teacher starts from the rollout's state at the sampled interval. - x_selected = pair["pdd_trajectory"]["visual"][k].unsqueeze(0) + x_selected = pair["pdd_trajectory"][k].unsqueeze(0) expected = pdd_loss( predictions, x, - grids["visual"], + grid, start, k, lambda state, sigma: teacher(state, sigma.expand(1)), diff --git a/tests/fast/distillation/test_pdd_rollout.py b/tests/fast/distillation/test_pdd_rollout.py index 33e82b7e5..6128fb5d9 100644 --- a/tests/fast/distillation/test_pdd_rollout.py +++ b/tests/fast/distillation/test_pdd_rollout.py @@ -56,7 +56,7 @@ def test_converter_validates_grid_and_complete_trajectory(monkeypatch): diffusion_model_family="qwen_image21", hf_checkpoint="unused", diffusion_height=32, pdd_num_intervals=32 ) pair = pdd_rollout.convert_samples_to_train_data(args, [sample])["train_data"][0] - torch.testing.assert_close(pair["pdd_trajectory"]["visual"], sample.dit_trajectory.latents) + torch.testing.assert_close(pair["pdd_trajectory"], sample.dit_trajectory.latents) blocks = expand_trajectories([pair], intervals=32, block_size=4) assert [block["pdd_start"] for block in blocks] == list(range(0, 32, 4)) for field, value in [ From a705597314ff84612daf5b9f62da2ea7bdc09bd8 Mon Sep 17 00:00:00 2001 From: niehen6174 <1639206518@qq.com> Date: Fri, 13 Nov 2026 19:54:29 +0800 Subject: [PATCH 3/3] test(pdd): consolidate the PDD tests into one CPU file and the SGLang GPU smoke - One tests/fast/distillation/test_pdd.py replaces three files: interval math, teacher target, engine cached-head steps, timestep matching, trajectory validation, the LoRA student (meta init, trainable and checkpointed parameters), arguments, and the eight-update loop against an independent reference. - Drop the FSDP one/two-rank parity worker: the SGLang smoke already trains the LoRA student through one-rank FSDP and checks every interval of the next rollout, and FSDP sharding itself is covered by the existing FSDP tests. - Remove pdd_loss, which only the tests used; the loss hook composes teacher_mean_velocity and interval_loss directly. --- docs/developer/pdd.md | 23 +- miles/distillation/pdd.py | 28 -- .../backends/fsdp_utils/_pdd_worker.py | 230 ---------- .../fast-gpu/backends/fsdp_utils/test_pdd.py | 43 -- .../test_miles_pdd_integration.py | 342 --------------- tests/fast/distillation/test_pdd.py | 394 +++++++++++++++--- tests/fast/distillation/test_pdd_rollout.py | 83 ---- 7 files changed, 339 insertions(+), 804 deletions(-) delete mode 100644 tests/fast-gpu/backends/fsdp_utils/_pdd_worker.py delete mode 100644 tests/fast-gpu/backends/fsdp_utils/test_pdd.py delete mode 100644 tests/fast/distillation/test_miles_pdd_integration.py delete mode 100644 tests/fast/distillation/test_pdd_rollout.py diff --git a/docs/developer/pdd.md b/docs/developer/pdd.md index 1b0aeaa9c..beee72e55 100644 --- a/docs/developer/pdd.md +++ b/docs/developer/pdd.md @@ -115,23 +115,20 @@ engine/trainer parity; later blocks also include rollout staleness. ## Verification and limits ```bash -python -m pytest tests/fast/distillation -python -m pytest tests/fast-gpu/backends/fsdp_utils/test_pdd.py +python -m pytest tests/fast/distillation/test_pdd.py python -m pytest tests/fast-gpu/backends/sglang_diffusion_utils/test_pdd_sglang_loop.py ``` -CPU tests cover detached teacher supervision, selected-head gradients, signed -nonuniform grids, eight block updates from rollout states against an independent -optimizer loop (the test plays the actor's teacher solve), the engine's cached -interval steps, trajectory validation, timestep matching and unsupported configurations. The FSDP -GPU test compares tiny-model updates with an unsharded reference on one and two -ranks, loading the student through the model-transform hook (two-rank case skips -with fewer GPUs). The SGLang GPU smoke runs real Qwen-Image 2.1 native stages, the -response parser, one-rank FSDP, the PDD loss and the Miles weight iterator into +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. -All GPU cases skip when CUDA is unavailable. +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/miles/distillation/pdd.py b/miles/distillation/pdd.py index 7e8f0fc3a..ba0eb02b6 100644 --- a/miles/distillation/pdd.py +++ b/miles/distillation/pdd.py @@ -76,31 +76,3 @@ def interval_loss(predictions: torch.Tensor, selected: int, target: 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) - - -def pdd_loss( - predictions: torch.Tensor, - x_start: torch.Tensor, - grid: torch.Tensor, - start: int, - selected: int, - teacher: Callable, - *, - x_selected: torch.Tensor | None = None, - solver: str = "midpoint", -) -> torch.Tensor: - """Per-sample loss for one uniformly sampled intra-block interval, shared across the microbatch. - - The caller supplies predictions from ONE student forward at (x_start, grid[start]). - The teacher starts from ``x_selected`` (e.g. the rollout's state at that interval), or - else from the earlier heads' update under stop-gradient. Only the selected head and - its shared backbone receive gradients from this Monte Carlo loss. - """ - validate_grid(grid) - if not 0 <= start <= selected < len(grid) - 1: - raise ValueError("require 0 <= start <= selected < num_intervals") - with torch.no_grad(): - if x_selected is None: - x_selected = block_update(x_start.detach(), predictions.detach(), grid, start, selected) - target = teacher_mean_velocity(teacher, x_selected, grid[selected], grid.diff()[selected], solver) - return interval_loss(predictions, selected, target) diff --git a/tests/fast-gpu/backends/fsdp_utils/_pdd_worker.py b/tests/fast-gpu/backends/fsdp_utils/_pdd_worker.py deleted file mode 100644 index 33212fbf4..000000000 --- a/tests/fast-gpu/backends/fsdp_utils/_pdd_worker.py +++ /dev/null @@ -1,230 +0,0 @@ -"""Tiny-Qwen FSDP parity for the Miles PDD path, loaded through PDD's generic loader hooks. - -Run with torchrun --standalone --nproc-per-node=1 (or 2). Uses a random tiny model; -this verifies FSDP numerics, not pretrained image quality. -""" - -import argparse -import json -import os -from pathlib import Path -from types import SimpleNamespace - -import torch -import torch.distributed as dist -from diffusers import QwenImage21Transformer2DModel -from torch.distributed.checkpoint.state_dict import StateDictOptions, get_model_state_dict -from torch.distributed.device_mesh import init_device_mesh - -from miles.backends.fsdp_utils.configs.qwen_image21 import QwenImage21TrainPipelineConfig -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.model_backend import DiffusersModelBackend -from miles.backends.fsdp_utils.model_loader import load_fsdp_models -from miles.distillation import integration -from miles.distillation.integration import install_student -from miles.distillation.pdd import pdd_loss - - -def tiny(dtype=torch.float32): - torch.manual_seed(72) - return QwenImage21Transformer2DModel( - in_channels=4, - out_channels=4, - num_layers=1, - attention_head_dim=16, - num_attention_heads=2, - context_in_dim=16, - axes_dims_rope=(4, 6, 6), - mlp_ratio=2, - ).to(dtype=dtype) - - -class Backend(DiffusersModelBackend): - def load_component(self, component, *, checkpoint_path, master_dtype, materialize_weights): - return tiny(master_dtype) - - -class Metrics: - def emit_mean(self, *args, **kwargs): - pass - - -def full(model): - return get_model_state_dict(model, options=StateDictOptions(full_state_dict=True)) - - -def main(): - parser = argparse.ArgumentParser() - parser.add_argument("--output", type=Path, required=True) - cli = parser.parse_args() - rank = int(os.environ["LOCAL_RANK"]) - torch.cuda.set_device(rank) - dist.init_process_group("nccl", device_id=torch.device("cuda", rank)) - device = torch.device("cuda", rank) - mesh = init_device_mesh("cuda", (dist.get_world_size(),), mesh_dim_names=("fsdp",)) - parallel = SimpleNamespace(get_mesh=lambda name: mesh, get_optional_mesh=lambda name: None) - args = SimpleNamespace( - diffusion_model_family="qwen_image21", - fsdp_master_dtype="fp32", - fsdp_param_dtype="fp32", - fsdp_reduce_dtype="fp32", - custom_train_model_transform_path="miles.distillation.integration.install_student", - diffusion_forward_dtype="bf16", - update_weight_target_modules=["transformer"], - fsdp_attention_backend=None, - gradient_checkpointing=True, - use_lora=False, - pdd_num_intervals=32, - pdd_block_size=4, - offload_train=False, - diffusion_height=64, - diffusion_width=64, - seed=42, - hf_checkpoint="tiny", - ) - config = QwenImage21TrainPipelineConfig() - config.configure(args) - config.prepare_cond_kwargs = lambda cond, device: cond # synthetic conditioning, not a rollout env - backend = Backend(config) - models = load_fsdp_models(args, backend, config, parallel, checkpoint_path="tiny", trainable=True) - teachers = load_fsdp_models(args, backend, config, parallel, checkpoint_path="tiny", trainable=False) - model = models["transformer"] - teacher = teachers["transformer"] - reference = tiny().to(device) - install_student(reference, args) - reference.load_state_dict(full(model)) - refteacher = tiny().to(device).eval().requires_grad_(False) - refteacher.load_state_dict(full(teacher)) - optimizer = torch.optim.AdamW(model.parameters(), lr=1e-4, weight_decay=0, foreach=False) - refopt = torch.optim.AdamW(reference.parameters(), lr=1e-4, weight_decay=0, foreach=False) - grid = torch.linspace(1, 0, 33, device=device) - integration.make_grid = lambda *args: grid # the tiny model has no scheduler config - torch.manual_seed(100 + rank) - cond = { - "encoder_hidden_states": torch.randn(1, 3, 16, device=device), - "encoder_hidden_states_mask": None, - "img_mask": torch.tensor([[False] * 3 + [True] * 4], device=device), - "img_shapes": [[(1, 4, 4)]], - } - # A rollout trajectory: every interval start plus the endpoint, BF16-rounded like the engine's noise. - trajectory = torch.randn(33, 16, 4).bfloat16().float() - env = SimpleNamespace(pos_cond_kwargs=cond) - ctx = DiffusionLossContext( - models=models, - train_pipeline_config=config, - sde_backend=None, - args=args, - forward_dtype=torch.bfloat16, - device=device, - ) - max_output = 0.0 - max_grad = 0.0 - for start in range(0, 32, 4): - optimizer.zero_grad() - refopt.zero_grad() - pair = { - "sample_index": rank, - "pdd_start": start, - "pdd_trajectory": trajectory, - "denoising_env": env, - } - prepared = prepare_pdd_batch(ctx, [pair], microbatch_id=0, optim_step_idx=0) - x = prepared.latents["visual"] - torch.testing.assert_close(x[0].cpu(), trajectory[start], rtol=0, atol=0) - with torch.autocast("cuda", dtype=torch.bfloat16): - - def teacher_forward(latents, timesteps): - # The actor's teacher forward: the sharded frozen teacher on this batch's conditioning. - return config.compute_noise_pred( - model=teacher, - latents_input=latents, - timesteps_input=timesteps, - pos_cond=cond, - neg_cond=None, - joint_cond=None, - use_cfg=False, - cfg_batching=False, - guidance_scale=1.0, - true_cfg_scale=None, - ) - - with torch.no_grad(): - target = prepared.teacher_solver(teacher_forward) - pred = config.compute_noise_pred( - model=model, - latents_input={"visual": x}, - timesteps_input=prepared.timesteps_for_model, - pos_cond=cond, - neg_cond=None, - joint_cond=None, - use_cfg=False, - cfg_batching=False, - guidance_scale=1.0, - true_cfg_scale=1.0, - ) - # Unsharded student: keep the image-token tail, split into [head, batch, token, channel]. - model_sigma = prepared.timesteps_for_model["visual"] - refpred = reference(hidden_states=x, timestep=model_sigma, return_dict=False, **cond)[0] - refpred = refpred[:, -16:].reshape(1, 16, 32, 4).permute(2, 0, 1, 3) - loss = pdd_loss_formula( - ctx, - [pair], - prepared, - new_pred=pred, - old_pred=None, - ref_pred=None, - teacher_pred=target, - metrics=Metrics(), - optim_step_idx=0, - train_output_inputs=[], - ) - - def tf(state, sigma): - return refteacher(hidden_states=state, timestep=sigma.expand(1), return_dict=False, **cond)[0][ - :, -16: - ].float() - - selected = prepared.extras["selected"] - x_selected = trajectory[selected].to(device).unsqueeze(0) - refloss = pdd_loss(refpred, x, grid, start, selected, tf, x_selected=x_selected).sum() - rawref = refpred.permute(1, 2, 0, 3).flatten(2) - err = (pred["visual"] - rawref).abs().max().item() - max_output = max(max_output, err) - torch.testing.assert_close(pred["visual"], rawref, rtol=0, atol=0) - torch.testing.assert_close(loss, refloss, rtol=0, atol=0) - loss.backward() - refloss.backward() - for (name, p), (rname, r) in zip(model.named_parameters(), reference.named_parameters(), strict=True): - assert name == rname and (p.grad is None) == (r.grad is None), name - if p.grad is not None: - dist.all_reduce(r.grad) - r.grad.div_(dist.get_world_size()) - grad = p.grad.full_tensor() - max_grad = max(max_grad, (grad - r.grad).abs().max().item()) - # Losses match bitwise; the BF16-autocast backward sums in a different order under FSDP - # (observed up to 1.3e-3 of the largest entry, well under one BF16 ulp). - scale = r.grad.abs().max().item() - torch.testing.assert_close(grad, r.grad, rtol=2e-5, atol=2e-6 + 5e-3 * scale, msg=name) - optimizer.step() - refopt.step() - assert all(p.grad is None for p in teacher.parameters()) - for name, p in full(model).items(): - torch.testing.assert_close(p, reference.state_dict()[name], rtol=2e-5, atol=2e-6, msg=name) - if rank == 0: - report = { - "state": "passed", - "world_size": dist.get_world_size(), - "updates": 8, - "max_forward_abs_diff": max_output, - "max_gradient_abs_diff_rank0": max_grad, - "teacher_frozen": True, - "model": "random tiny Qwen-Image 2.1", - } - (cli.output / "verification.json").write_text(json.dumps(report, indent=2)) - print(json.dumps(report), flush=True) - dist.destroy_process_group() - - -if __name__ == "__main__": - main() diff --git a/tests/fast-gpu/backends/fsdp_utils/test_pdd.py b/tests/fast-gpu/backends/fsdp_utils/test_pdd.py deleted file mode 100644 index bb92fd571..000000000 --- a/tests/fast-gpu/backends/fsdp_utils/test_pdd.py +++ /dev/null @@ -1,43 +0,0 @@ -"""PDD FSDP parity through the generic loader hooks.""" - -from tests.ci.ci_register import register_cuda_ci - -register_cuda_ci(est_time=90, suite="stage-b-5-gpu-h200", labels=["fsdp"]) - -import json -import os -import subprocess -import sys -from pathlib import Path - -import pytest -import torch - - -@pytest.mark.parametrize("world_size", [1, 2]) -def test_pdd_fsdp_parity(tmp_path, world_size): - if torch.cuda.device_count() < world_size: - pytest.skip(f"Requires {world_size} CUDA devices") - result = subprocess.run( - [ - sys.executable, - "-m", - "torch.distributed.run", - "--standalone", - f"--nproc-per-node={world_size}", - str(Path(__file__).with_name("_pdd_worker.py")), - "--output", - str(tmp_path), - ], - env={**os.environ, "PYTHONUNBUFFERED": "1"}, - capture_output=True, - text=True, - timeout=300, - ) - assert result.returncode == 0, result.stdout + result.stderr - report = json.loads((tmp_path / "verification.json").read_text()) - assert report["state"] == "passed" and report["world_size"] == world_size - - -if __name__ == "__main__": - sys.exit(pytest.main([__file__, "-v"])) diff --git a/tests/fast/distillation/test_miles_pdd_integration.py b/tests/fast/distillation/test_miles_pdd_integration.py deleted file mode 100644 index 6aacad70b..000000000 --- a/tests/fast/distillation/test_miles_pdd_integration.py +++ /dev/null @@ -1,342 +0,0 @@ -"""Trainer side: eight block updates from rollout states match an independent optimizer loop. - -The test plays the actor: it runs the prepare hook's teacher solver with its own teacher forward, -then hands the result to the formula as ``teacher_pred``. -""" - -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.distillation import integration -from miles.distillation.integration import expand_train_pairs, expand_trajectories, install_student -from miles.distillation.pdd import ParallelLinear, pdd_loss - - -@pytest.fixture(autouse=True) -def linear_grid(monkeypatch): - monkeypatch.setattr(integration, "make_grid", lambda *args: torch.linspace(1, 0, 33)) - - -class Model(nn.Module): - def __init__(self): - super().__init__() - self.config = SimpleNamespace(in_channels=2, patch_size=1) - self.base = nn.Linear(2, 2) - self.head = ParallelLinear(nn.Linear(2, 2), 32) - - def forward(self, x, sigma): - return self.head(self.base(x) + sigma.reshape(-1, 1, 1)) - - -class Config: - def compute_noise_pred(self, *, model, latents_input, timesteps_input, **kw): - return {"visual": model(latents_input["visual"].float(), timesteps_input["visual"])} - - def prepare_cond_kwargs(self, cond, device): - return cond - - -class Teacher(nn.Module): - def __init__(self): - super().__init__() - self.scale = nn.Parameter(torch.tensor(0.3), requires_grad=False) - self.calls = [] - - def forward(self, x, sigma): - self.calls.append((x.detach().clone(), sigma.detach().clone())) - return self.scale * x + sigma.reshape(-1, 1, 1) - - -class Metrics: - def emit_mean(self, *args, **kwargs): - pass - - -def context(student, rollout=0): - return DiffusionLossContext( - models={"transformer": student}, - train_pipeline_config=Config(), - sde_backend=None, - device=torch.device("cpu"), - forward_dtype=torch.float32, - args=SimpleNamespace( - diffusion_model_family="qwen_image21", - hf_checkpoint="unused", - pdd_num_intervals=32, - pdd_block_size=4, - diffusion_height=32, - seed=42, - ), - rollout_id=rollout, - ) - - -def teacher_target(teacher, prepared): - """What the actor does with ``prepared.teacher_solver``, without grad.""" - with torch.no_grad(): - return prepared.teacher_solver( - lambda latents, timesteps: {"visual": teacher(latents["visual"], timesteps["visual"])} - ) - - -def raw_forward(model, prepared): - pred = model(prepared.latents["visual"], prepared.timesteps_for_model["visual"]) - return {"visual": pred.permute(1, 2, 0, 3).flatten(2)} - - -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_reference(): - torch.manual_seed(12) - student = Model() - reference = copy.deepcopy(student) - teacher = Teacher() - ctx = context(student) - opt = torch.optim.AdamW(student.parameters(), lr=1e-3, weight_decay=0) - refopt = torch.optim.AdamW(reference.parameters(), lr=1e-3, weight_decay=0) - pairs = [rollout_pair(i) for i in (2, 9)] - expanded = expand_train_pairs(ctx, 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) - start, k, grid = (prepared.extras[v] for v in ("start", "selected", "grid")) - x = prepared.latents["visual"] - torch.testing.assert_close(x[0], pair["pdd_trajectory"][4 * step], rtol=0, atol=0) - assert start == 4 * step and not x.requires_grad - predictions = reference(x, prepared.timesteps_for_model["visual"]) - # The teacher starts from the rollout's state at the sampled interval. - x_selected = pair["pdd_trajectory"][k].unsqueeze(0) - expected = pdd_loss( - predictions, - x, - grid, - start, - k, - lambda state, sigma: teacher(state, sigma.expand(1)), - x_selected=x_selected, - ) - calls = len(teacher.calls) - target = teacher_target(teacher, prepared) - torch.testing.assert_close(teacher.calls[calls][0], x_selected, rtol=0, atol=0) - loss = pdd_loss_formula( - ctx, - [pair], - prepared, - new_pred=raw_forward(student, prepared), - old_pred=None, - ref_pred=None, - teacher_pred=target, - metrics=Metrics(), - optim_step_idx=0, - train_output_inputs=[], - ) - torch.testing.assert_close(loss, expected.sum(), rtol=0, atol=0) - (loss / 2).backward() - (expected.sum() / 2).backward() - for a, b in zip(student.parameters(), reference.parameters(), strict=True): - torch.testing.assert_close(a.grad, b.grad, rtol=0, atol=0) - 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(): - student = Model() - pair = dict(rollout_pair(99), pdd_start=0) - chosen = prepare_pdd_batch(context(student, 7), [pair], microbatch_id=0, optim_step_idx=0).extras["selected"] - torch.randn(500) # unrelated process RNG must not affect a resumed rollout - assert ( - prepare_pdd_batch(context(student, 7), [pair], microbatch_id=0, optim_step_idx=0).extras["selected"] == chosen - ) - choices = { - prepare_pdd_batch(context(student, r), [pair], microbatch_id=0, optim_step_idx=0).extras["selected"] - for r in range(32) - } - assert choices == {0, 1, 2, 3} - - -def test_heads_installed_on_meta_before_sharding(): - with torch.device("meta"): - model = nn.Module() - model.proj_out = nn.Linear(4, 2) - model.config = SimpleNamespace(patch_size=1, in_channels=2) - install_student(model, SimpleNamespace(diffusion_model_family="qwen_image21", pdd_num_intervals=32)) - assert all(p.is_meta for p in model.parameters()) - assert model.proj_out.parallel.weight.shape == (32, 2, 4) - - -def test_dp_split_precedes_trajectory_expansion(): - from miles.utils.train_data_utils import TrainDataDPSplitter - - pairs = [{"sample_index": i} for i in range(8)] - shards = TrainDataDPSplitter().split_by_dp({"train_data": pairs}, 2) - for shard in shards: - expanded = expand_trajectories(shard["train_data"], intervals=32, block_size=4) - for start in range(8): - window = expanded[start * 4 : (start + 1) * 4] - assert [p["sample_index"] for p in window] == [p["sample_index"] for p in shard["train_data"]] - assert all(p["pdd_start"] == start * 4 for p in window) - with pytest.raises(ValueError, match="distinct lane"): - expand_trajectories([pairs[0], pairs[0]], intervals=32, block_size=4) - - -def valid_args(): - return SimpleNamespace( - diffusion_model_family="qwen_image21", - diffusion_task="t2i", - train_only=False, - 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, - micro_batch_size_sample=None, - sequence_parallel_size=1, - use_lora=True, - colocate=True, - lora_ipc_weight_sync=True, - sglang_lora_merge_mode="dynamic", - use_ema=False, - ref_load=None, - ref_mode="none", - teacher_lora_adapter_paths=None, - lora_adapter_paths=None, - diffusion_recompute_old_log_prob=False, - diffusion_kl_beta=0, - 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", - teacher_load=None, - 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", - diffusion_step_strategy_path=None, - custom_generate_function_path=None, - group_rm=False, - rollout_patch_group=None, - rollout_function_path="miles.rollout.sglang_rollout.generate_rollout", - custom_convert_samples_to_train_data_path=None, - custom_rm_path=None, - custom_train_model_transform_path=None, - fsdp_param_dtype=None, - rollout_return_full_trajectory=False, - num_steps_per_rollout=None, - global_batch_size=None, - rollout_batch_size=8, - ) - - -def configure(args, **overrides): - """set_default_diffusion_args -> user overrides stand -> miles_validate_args, as in parse_args.""" - from miles.distillation.integration import set_pdd_defaults, validate_pdd_args - - 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) - - -def test_defaults_select_sglang_rollout_and_eight_updates(): - args = valid_args() - configure(args) - assert args.global_batch_size == 8 and args.num_steps_per_rollout == 8 - assert args.teacher_load == args.hf_checkpoint - assert args.rollout_function_path == "miles.rollout.sglang_diffusion_rollout.generate_rollout" - assert args.rollout_patch_groups == ["pdd_qwen_image21"] and args.rollout_return_full_trajectory - from miles.backends.fsdp_utils.loss_hub import LOSS_HOOKS - - hooks = LOSS_HOOKS[("pdd", "actor")] - assert (hooks.prepare, hooks.formula, hooks.train_input) == ( - prepare_pdd_batch, - pdd_loss_formula, - expand_train_pairs, - ) - assert args.custom_train_model_transform_path.endswith("integration.install_student") - assert args.fsdp_param_dtype == "fp32" - - -@pytest.mark.parametrize( - "name,value", - [ - ("sequence_parallel_size", 2), - ("use_lora", False), - ("lora_ipc_weight_sync", False), - ("sglang_lora_merge_mode", "merge"), - ("train_only", True), - ("pdd_block_size", 8), - ("diffusion_guidance_scale", 4), - ("custom_rm_path", "miles.rollout.rm_hub.other"), - ("teacher_load", "other-model"), - ("global_batch_size", 1), - ("num_steps_per_rollout", 1), - ("diffusion_height", 512), - ("diffusion_num_steps", 40), - ("diffusion_noise_level", 0.1), - ("rollout_num_gpus_per_engine", 2), - ("rollout_microgroup_size", 2), - ("sglang_dit_precision", "bf16"), - ("rollout_patch_group", "qwen_image21"), - ], -) -def test_unvalidated_modes_fail_before_gpu_load(name, value): - with pytest.raises(ValueError): - configure(valid_args(), **{name: value}) - - -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) - - # The loader's order: LoRA first, then the model-transform hook on the unwrapped model. - model = get_peft_model(Tiny(), LoraConfig(r=2, lora_alpha=2, target_modules=["to_q"])) - install_student( - model.get_base_model(), SimpleNamespace(diffusion_model_family="qwen_image21", pdd_num_intervals=32) - ) - 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 diff --git a/tests/fast/distillation/test_pdd.py b/tests/fast/distillation/test_pdd.py index 9b8eeb8ca..24b90f30d 100644 --- a/tests/fast/distillation/test_pdd.py +++ b/tests/fast/distillation/test_pdd.py @@ -1,86 +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=5, suite="stage-a-cpu", labels=[]) +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.distillation.pdd import ParallelLinear, block_update, pdd_loss, teacher_mean_velocity +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.mark.parametrize("solver", ["euler", "midpoint"]) -@pytest.mark.parametrize("descending", [False, True]) -def test_target_uses_detached_student_state_and_signed_step(solver, descending): - grid = torch.tensor([0.0, 0.2, 0.7, 1.0]) - if descending: - grid = grid.flip(0) - x = torch.tensor([[1.0, 2.0]], requires_grad=True) - predictions = torch.tensor([[[2.0, 3.0]], [[4.0, 5.0]], [[6.0, 7.0]]], requires_grad=True) - teacher_weight = nn.Parameter(torch.tensor(0.5)) - seen = [] - def teacher(state, time): - seen.append((state.detach().clone(), torch.is_grad_enabled())) - return teacher_weight * state + time - - loss = pdd_loss(predictions, x, grid, 0, 1, teacher, solver=solver).mean() - expected_state = x.detach() + (grid[1] - grid[0]) * predictions[0].detach() - velocity = 0.5 * expected_state + grid[1] - if solver == "midpoint": - h = grid[2] - grid[1] - velocity = 0.5 * (expected_state + h * 0.5 * velocity) + grid[1] + h * 0.5 - torch.testing.assert_close(seen[0][0], expected_state) - torch.testing.assert_close(loss, (predictions[1] - velocity).square().mean()) - assert len(seen) == (1 if solver == "euler" else 2) - assert all(not enabled for _, enabled in seen) - loss.backward() - assert x.grad is None and teacher_weight.grad is None - assert predictions.grad[0].count_nonzero() == 0 - assert predictions.grad[1].count_nonzero() > 0 - assert predictions.grad[2].count_nonzero() == 0 - - -def test_head_initialization_and_shared_backbone_gradient(): - source = nn.Linear(3, 2) - head = ParallelLinear(source, 4) - hidden = torch.randn(5, 3, requires_grad=True) - outputs = head(hidden) - for output in outputs: - torch.testing.assert_close(output, source(hidden)) - outputs[2].square().mean().backward() - assert hidden.grad.abs().sum() > 0 - assert head.weight.grad[2].abs().sum() > 0 - assert head.weight.grad[[0, 1, 3]].count_nonzero() == 0 +@pytest.fixture(autouse=True) +def linear_grid(monkeypatch): + monkeypatch.setattr(integration, "make_grid", lambda *args: GRID) + + +# --- interval math ------------------------------------------------------------------------------------- @pytest.mark.parametrize("descending", [False, True]) -@pytest.mark.parametrize("block_size", [1, 2, 4, 8]) -def test_oracle_mean_velocities_follow_exact_linear_ode_across_block_sizes(descending, block_size): - """Independent analytic oracle: dx/dt = a*x on a nonuniform grid.""" +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 = torch.tensor(-0.7, dtype=torch.float64) - initial = torch.tensor([[1.3, -2.1]], dtype=torch.float64) + a, x0 = torch.tensor(-0.7, dtype=torch.float64), torch.tensor([[1.3, -2.1]], dtype=torch.float64) - def oracle(state, time): - # Each head is the analytic integral from its own interval, relative to - # this call's block-start state. No sampler helpers construct the oracle. - left = torch.exp(a * (grid[:-1] - time)) - right = torch.exp(a * (grid[1:] - time)) - means = (right - left) / (grid[1:] - grid[:-1]) - return means[:, None, None] * state + 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 - actual = initial - for start in range(0, 8, block_size): - actual = block_update(actual, oracle(actual, grid[start]), grid, start, start + block_size) - expected = initial * torch.exp(a * (grid[-1] - grid[0])) - torch.testing.assert_close(actual, expected, rtol=1e-12, atol=1e-12) + 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_invalid_inputs_fail_instead_of_broadcasting(): - with pytest.raises(ValueError): - pdd_loss(torch.zeros(3, 2, 1), torch.zeros(2, 1), torch.tensor([0.0, 0.5, 0.4, 1.0]), 0, 1, None) +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): - teacher_mean_velocity(lambda x, t: x[:, :1], torch.zeros(2, 3), torch.tensor(0.0), torch.tensor(0.1)) + configured(**{name: value}) diff --git a/tests/fast/distillation/test_pdd_rollout.py b/tests/fast/distillation/test_pdd_rollout.py deleted file mode 100644 index 6128fb5d9..000000000 --- a/tests/fast/distillation/test_pdd_rollout.py +++ /dev/null @@ -1,83 +0,0 @@ -"""Rollout side: engine heads, trajectory conversion, timestep matching and resume signature.""" - -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 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_trajectories -from miles.distillation.pdd import block_update -from miles.rollout import pdd_rollout - - -def test_engine_interval_steps_match_pdd_and_see_live_weight_updates(): - """The engine's 32 Euler steps on one cached forward per block reproduce every interval start.""" - torch.manual_seed(8) - projection = PDDProjection(torch.nn.Linear(3, 2)) - grid = torch.linspace(1, 0, 33).square() - hidden, state = torch.randn(1, 5, 3), torch.randn(1, 5, 2) - x = state - for interval in range(32): - start = interval - interval % 4 - if interval == start: - head = projection(hidden) - torch.testing.assert_close(head, 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) - before = projection(hidden).clone() - with torch.no_grad(): - projection.parallel.weight.add_(0.5) - assert not torch.equal(before, projection(hidden)) - assert set(projection.state_dict()) == {"parallel.weight", "parallel.bias"} - - -def test_converter_validates_grid_and_complete_trajectory(monkeypatch): - grid = torch.linspace(1, 0, 33) - monkeypatch.setattr(integration, "make_grid", lambda *args: 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( - diffusion_model_family="qwen_image21", hf_checkpoint="unused", diffusion_height=32, 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) - blocks = expand_trajectories([pair], intervals=32, block_size=4) - assert [block["pdd_start"] for block in blocks] == list(range(0, 32, 4)) - for field, value in [ - ("sigmas", grid[::4]), - ("sigmas", grid + 0.01), - ("latents", torch.randn(9, 4, 2)), - ("latents", torch.full((33, 4, 2), float("nan"))), - ("latent_step_indices", torch.arange(1, 34)), - ]: - bad = copy.deepcopy(sample) - setattr(bad.dit_trajectory, field, value) - with pytest.raises(ValueError): - pdd_rollout.convert_samples_to_train_data(args, [bad]) - - -def test_engine_timesteps_reproduce_trainer_bf16_sigma(): - # 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() - embedded = embedded_sigmas(engine_timesteps(sigmas)) - fixed = embedded != sigmas.bfloat16().float() - assert naive.float().mean() > 0.2 and fixed.float().mean() < 0.05 and not (fixed & ~naive).any() - # Unreachable sigmas fall back to the nearest embeddable value, which the trainer adopts. - assert (embedded - sigmas).abs().max() < 8e-3