diff --git a/docs/advanced/sde-backend.md b/docs/advanced/sde-backend.md index ffe9cbab1..4e7eba88c 100644 --- a/docs/advanced/sde-backend.md +++ b/docs/advanced/sde-backend.md @@ -33,7 +33,7 @@ Implementation: `miles/backends/fsdp_utils/sde_step_backend.py`. Override with |---|---|---|---| | Flow-SDE | `sde` (default) | `FlowSdeStepBackend` | Transition noise std η·√(σ/(1−σ))·√(−dt) with the rollout's recorded σ (the grid's second σ replaces the denominator's σ at σ = 1); [Flow-GRPO](https://arxiv.org/abs/2505.05470) | | CPS | `cps` | `CpsSdeStepBackend` | Transition noise std σ_next·sin(η·π/2); log-prob is −(x−μ)², without the Gaussian constants or the 1/(2σ²) scale (forces `--diffusion-log-prob-no-const`); [FlowCPS](https://arxiv.org/abs/2509.05952) | -| ODE | `ode` | `FlowSdeStepBackend` (placeholder; NFT never calls it) | Deterministic; NFT (or a custom loss formula) only — with the Flow-GRPO loss it is rejected at parse time | +| ODE | `ode` | `FlowSdeStepBackend` (placeholder; NFT and DMD2 never call it) | Deterministic; NFT, DMD2 or a custom loss formula only — with the Flow-GRPO loss it is rejected at parse time | `--diffusion-noise-level` (η) sets the SDE noise scale. DanceGRPO-style constant-η schedules use the same `sde` backend with a tuned η diff --git a/docs/developer/contributor-guide.md b/docs/developer/contributor-guide.md index 041f47bba..f23aaaeec 100644 --- a/docs/developer/contributor-guide.md +++ b/docs/developer/contributor-guide.md @@ -18,7 +18,7 @@ miles_diffusion/ │ │ │ ├── actor.py # FSDPTrainRayActor: wrap, forward, loss, step │ │ │ ├── configs/ # TrainPipelineConfig per model family │ │ │ ├── models/ # native model packages (ltx) + diffusers parallel plans -│ │ │ ├── loss_hub/ # flow_grpo / nft / sft objectives +│ │ │ ├── loss_hub/ # loss hooks per (loss_type, role): flow_grpo / nft / sft / dmd2 │ │ │ ├── sequence_parallel/ # USP = Ulysses × Ring │ │ │ ├── monkey_patches/ # FSDP2 param-dtype patch (torch 2.11 gated) │ │ │ ├── mixed_precision.py # per-parameter dtype map compilation diff --git a/docs/fsdp_model_roles.md b/docs/fsdp_model_roles.md index 372ee4c10..684039068 100644 --- a/docs/fsdp_model_roles.md +++ b/docs/fsdp_model_roles.md @@ -37,9 +37,8 @@ access `ctx.reference_models` by component name. A third source, the teacher (`--teacher-load`, with `--teacher-lora-adapter-path` for its adapters), is loaded by `--loss-type dmd2`, without adapters, into its critic group, which -scores the student's samples with it. Otherwise it has no built-in consumer: `--teacher-load` -requires a custom prepare/loss/train-output hook, which reads it from `ctx.teacher_models`, and -teacher inference should run inside `torch.no_grad()`. +scores the student's samples with it. Otherwise only a custom hook reads it, from `ctx.teacher_models`, +and teacher inference should run inside `torch.no_grad()`. Each source may load pretrained PEFT LoRA adapters, one plain PEFT directory (what `save_pretrained` writes) per `--update-weight-target-module` entry, in the same order: diff --git a/docs/user-guide/cli-reference.md b/docs/user-guide/cli-reference.md index ab97f92d2..4916f691a 100644 --- a/docs/user-guide/cli-reference.md +++ b/docs/user-guide/cli-reference.md @@ -100,7 +100,7 @@ See [Dtype Control](../advanced/dtype-control.md). | Flag | Default | What | |---|---|---| -| `--loss-type` | `policy_loss` | `policy_loss` (Flow-GRPO), `nft`, `sft_loss`, `custom_loss`, `dmd2`. | +| `--loss-type` | `policy_loss` | `policy_loss` (Flow-GRPO), `nft`, `sft_loss`, `custom_loss`, `dmd2`; selects each trainer group's hooks from the loss hub, only `custom_loss` reads the four `--custom-*-path` hook flags. | | `--advantage-estimator` | `grpo` | Only `grpo` today. | | `--diffusion-clip-range` | `1e-4` | PPO ratio clip. | | `--diffusion-adv-clip-max` | `5.0` | Advantage clamp. | @@ -274,13 +274,13 @@ See [Dtype Control](../advanced/dtype-control.md). | `--ref-load` | str | – | HF pipeline checkpoint of an independent frozen reference model. Requires `--ref-mode ref`. | | `--ref-lora-adapter-path` | str+ | – | PEFT adapter directories applied to `--ref-load`, one per `--update-weight-target-module` entry, in order. | | `--ref-cpu-offload` | flag | off | Keep the reference shards in pinned CPU memory between forwards (FSDP `CPUOffloadPolicy`). | -| `--teacher-load` | str | – | HF pipeline checkpoint of a frozen teacher model, read only by custom prepare/loss/train-output hooks as `ctx.teacher_models`, so it requires `--custom-prepare-train-batch-path`, `--custom-loss-function-path` or `--custom-train-output-function-path`. | +| `--teacher-load` | str | – | HF pipeline checkpoint of a frozen teacher model, offered to the hooks as `ctx.teacher_models`; `--loss-type dmd2` scores the student's samples with it. | | `--teacher-lora-adapter-path` | str+ | – | PEFT adapter directories applied to `--teacher-load`, one per `--update-weight-target-module` entry, in order. | | `--teacher-cpu-offload` | flag | off | Keep the teacher shards in pinned CPU memory between forwards. | -| `--custom-prepare-train-batch-path` | str | – | Builds DiT inputs. | -| `--custom-loss-function-path` | str | – | Loss **formula** only — the DiT forward stays in the actor. | -| `--custom-train-input-postprocess-path` | str | – | 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 | – | 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[]`. | +| `--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-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` | | | `--diffusion-nft-timestep-strategy-path` | str | `…nft.drop_random_steps` | `(args, num_steps, generator) -> list[int]` returning the denoising steps each sample trains on, in training order; `generator` is seeded per sample. Built in: `drop_random_steps` (random order), `drop_final_steps` (schedule order, noisiest first). The final clean output (σ = 0) is never a training step. | | `--diffusion-nft-num-dropped-timesteps` | int | `0` | Steps the built-in strategies drop: random ones per sample for `drop_random_steps`, the final (lowest-noise) ones for `drop_final_steps`. | diff --git a/docs/user-guide/customization.md b/docs/user-guide/customization.md index cdc441dcf..97e33f8a8 100644 --- a/docs/user-guide/customization.md +++ b/docs/user-guide/customization.md @@ -33,8 +33,8 @@ signatures they expect, and the defaults they replace — in the same spirit as | **Model family** | `--train-pipeline-config-path` | Family `TrainPipelineConfig` | | | `--model-backend-path` | Model load / FSDP backend | -`--loss-type` (`policy_loss` / `nft` / `sft_loss` / `custom_loss` / `dmd2`) is the -shortcut that auto-fills several of the train-side paths; see § Training. +`--loss-type` (`policy_loss` / `nft` / `sft_loss` / `custom_loss` / `dmd2`) selects the train-side +hooks of each trainer group from the loss hub, and picks the default expand path; see § Training. *** @@ -226,27 +226,32 @@ def buffer_filter( ## Training -`--loss-type` picks the default prepare / formula / expand paths: - -| `--loss-type` | Expand pairs | Prepare | Loss formula | -|---|---|---|---| -| `policy_loss` (default) | Flow-GRPO built-in | `prepare_flow_grpo_batch` | `flow_grpo_loss_formula` | -| `nft` | `data_conversion_hub.nft.expand_samples_to_train_pairs` | `loss_hub.nft.prepare_nft_batch` | `nft_loss_formula` | -| `sft_loss` | none; convert `sft_rollout.convert_samples_to_train_data` | `loss_hub.sft.prepare_sft_batch` | `sft_loss_formula` | -| `custom_loss` | your expand (or convert) | your prepare | your formula | -| `dmd2` | `data_conversion_hub.dmd2.expand_samples_to_train_pairs` | `loss_hub.dmd2.prepare_generator_batch` | `dmd2_loss_formula` | - -`sft_loss` auto-fills nothing: it requires the convert, rollout-log, prepare and loss -paths, plus `--train-only` and a rollout function that runs no engines (e.g. -`miles.rollout.sft_rollout.generate_rollout`; see `scripts/run_diffusion_sft_wan22.py`). `custom_loss` behaves like `policy_loss`: -any hook left unset falls back to the Flow-GRPO built-in. `dmd2` also trains a `critic` group -before the actor on each rollout: it starts from `--critic-load` (default `--teacher-load`), -learns the student's samples with the SFT loss at `--critic-lr` (default `--lr`). On its last step -it keeps its own x0 predictions from that step's forward, before the update, and after training hands -them with the teacher's x0 at the same noisy inputs to the actor as `ctx.external_data["critic"]`. -The actor trains on those samples only (its train-input hook defaults to -`loss_hub.dmd2.select_scored_pairs`): it recomputes the student's x0 at the rollout's step and moves -it along their difference. +`--loss-type` picks the default expand path and selects each trainer group's hooks from the loss hub, +`miles.backends.fsdp_utils.loss_hub.LOSS_HOOKS`, keyed by `(loss_type, role)`. A group's hooks are +its prepare, its loss formula (the function `--custom-loss-function-path` names under `custom_loss`), +and optionally a train-input and a train-output hook: + +| `--loss-type` | Expand pairs | Prepare | Loss formula | Train-input / train-output | +|---|---|---|---|---| +| `policy_loss` (default) | Flow-GRPO built-in | `prepare_flow_grpo_batch` | `flow_grpo_loss_formula` | – | +| `nft` | `data_conversion_hub.nft.expand_samples_to_train_pairs` | `loss_hub.nft.prepare_nft_batch` | `nft_loss_formula` | – | +| `sft_loss` | none; convert `sft_rollout.convert_samples_to_train_data` | `loss_hub.sft.prepare_sft_batch` | `sft_loss_formula` | – | +| `custom_loss` | your expand (or convert) | your prepare | your formula | yours | +| `dmd2`, actor | `data_conversion_hub.dmd2.expand_samples_to_train_pairs` | `loss_hub.dmd2.prepare_generator_batch` | `dmd2_loss_formula` | `select_scored_pairs` / – | +| `dmd2`, critic | (the actor's pairs) | `loss_hub.dmd2.prepare_critic_batch` | `critic_loss_formula` | – / `score_last_step_samples` | + +`sft_loss` requires the convert and rollout-log paths, plus `--train-only` and a rollout function +that runs no engines (e.g. `miles.rollout.sft_rollout.generate_rollout`; see +`scripts/run_diffusion_sft_wan22.py`). `custom_loss` is the only loss type that reads the four hook +flags (`--custom-prepare-train-batch-path`, `--custom-loss-function-path`, +`--custom-train-input-postprocess-path`, `--custom-train-output-function-path`): any hook left unset +falls back to the Flow-GRPO built-in. `dmd2` also trains +a `critic` group before the actor on each rollout: it starts from `--critic-load` (default +`--teacher-load`), learns the student's samples with the SFT loss at `--critic-lr` (default `--lr`). +On its last step it keeps its own x0 predictions from that step's forward, before the update, and +after training its train-output hook hands them with the teacher's x0 at the same noisy inputs to the +actor as `ctx.external_data["critic"]`. The actor trains on those samples only (its train-input hook): +it recomputes the student's x0 at the rollout's step and moves it along their difference. DiT forward always stays in the FSDP actor; the loss hook only computes the objective. @@ -278,9 +283,9 @@ def prepare(ctx, batch, *, pad_to_len=None) -> PreparedBatch: ... ``` -Builds DiT inputs from train pairs. Defaults: -`miles.backends.fsdp_utils.loss_hub.flow_grpo.prepare_flow_grpo_batch` or the NFT -equivalent under `loss_hub.nft`. `PreparedBatch.latents`, `timesteps` and +Read only under `--loss-type custom_loss`; the other loss types take their prepare from the loss hub's table +above. Builds DiT inputs from train pairs. +`PreparedBatch.latents`, `timesteps` and `timesteps_for_model` are keyed by latent stream name: `"visual"`, plus e.g. `"audio"` for joint audio-video models. @@ -291,8 +296,9 @@ def loss_formula(ctx, batch, prepared, *, new_pred, old_pred, ref_pred, metrics, ... ``` -`new_pred`, `old_pred` and `ref_pred` are keyed by the same stream names as `prepared.latents`. -`old_pred` is `None` unless `--loss-type nft`; `ref_pred` is `None` with `--ref-mode none`. +Read only under `--loss-type custom_loss`. `new_pred`, `old_pred` and `ref_pred` are keyed by the same stream +names as `prepared.latents`. `old_pred` (the EMA forward) is `None` for a custom formula, since the trunk runs it +only under `--loss-type nft`; `ref_pred` is `None` with `--ref-mode none`. ### `--custom-train-input-postprocess-path` @@ -301,7 +307,8 @@ def train_input(ctx, train_pairs) -> list: ... ``` -Preprocesses this rank's train pairs, the rollout output after conversion, before they are split into +Read only under `--loss-type custom_loss`. Preprocesses this rank's train pairs, the rollout output after +conversion, before they are split into micro-batches and optimizer steps. It may filter, reorder or rewrite them, and returns the pairs to train on. `ctx` is the context the prepare, loss and train-output hooks get, so earlier trainer groups' outputs are already in `ctx.external_data`. The micro-batch schedule, the training forwards @@ -314,7 +321,8 @@ def train_output(ctx, train_pairs) -> Any: ... ``` -Runs without grad after this trainer group's train steps on a rollout. Every trainer group that +Read only under `--loss-type custom_loss`. Runs without grad after this trainer group's train steps on a +rollout. Every trainer group that trains later on the same rollout reads the return value of its paired rank (same rank, same train pairs) as `ctx.external_data[]`. Prepare and loss hooks see the current optimizer step as `ctx.optim_step_idx` and can leave inputs for this hook in `ctx.train_output_inputs`, which diff --git a/miles/backends/fsdp_utils/actor.py b/miles/backends/fsdp_utils/actor.py index 6ff8e8bba..ac5b0cf1e 100644 --- a/miles/backends/fsdp_utils/actor.py +++ b/miles/backends/fsdp_utils/actor.py @@ -40,7 +40,7 @@ ) from .ema import EMAOptimizer, reshard_model from .input_dtype_policy import apply_input_dtype_policy -from .loss_hub import DiffusionLossContext, flow_grpo_loss_formula, prepare_flow_grpo_batch +from .loss_hub import DiffusionLossContext, get_loss_hooks from .lr_scheduler import get_lr_scheduler from .metrics import new_metric_buffer from .mixed_precision import parse_dtype_from_str @@ -168,25 +168,7 @@ def init(self, args: Namespace, role: str, with_ref: bool = False) -> int: # ty self.model = torch.nn.ModuleDict(self.models) self.sde_backend = load_function(args.sde_step_backend_path)() - - self.custom_prepare_train_batch_func = ( - load_function(args.custom_prepare_train_batch_path) - if args.custom_prepare_train_batch_path is not None - else None - ) - self.custom_loss_formula_func = ( - load_function(args.custom_loss_function_path) if args.custom_loss_function_path is not None else None - ) - self.custom_train_input_postprocess_func = ( - load_function(args.custom_train_input_postprocess_path) - if args.custom_train_input_postprocess_path is not None - else None - ) - self.custom_train_output_func = ( - load_function(args.custom_train_output_function_path) - if args.custom_train_output_function_path is not None - else None - ) + self.loss_hooks = get_loss_hooks(args, role) if args.optimizer == "adam": self.optimizer = torch.optim.AdamW( @@ -386,8 +368,8 @@ def _train_core(self, rollout_id: int, rollout_data, external_data: dict[str, An dp_rank=self.parallel_state.dp_rank, external_data=external_data, ) - if self.custom_train_input_postprocess_func is not None: - train_pairs = self.custom_train_input_postprocess_func(loss_ctx, train_pairs) + if self.loss_hooks.train_input is not None: + train_pairs = self.loss_hooks.train_input(loss_ctx, train_pairs) num_pairs = len(train_pairs) @@ -504,9 +486,9 @@ def _train_core(self, rollout_id: int, rollout_data, external_data: dict[str, An reduced = {f"train/{self._metric_role_tag()}{key}": value for key, value in metrics.reduce().items()} self._log_metrics(rollout_id, reduced, step=self.global_step) - if self.custom_train_output_func is not None: + if self.loss_hooks.train_output is not None: with torch.no_grad(): - return self.custom_train_output_func(loss_ctx, train_pairs) + return self.loss_hooks.train_output(loss_ctx, train_pairs) def _maybe_legacy_window_pad_len(self, train_pairs: list, microbatch_ranges: list) -> int | None: """LEGACY 2D parity: the whole-window max cond seq_len (like the legacy tile path), or @@ -533,10 +515,7 @@ def _forward_train_pair_batch( old_log_prob_from_new: bool = False, ) -> torch.Tensor | None: """Run one prepared diffusion micro-batch.""" - if self.custom_prepare_train_batch_func is not None: - prepared = self.custom_prepare_train_batch_func(ctx, batch, pad_to_len=pad_to_len) - else: - prepared = prepare_flow_grpo_batch(ctx, batch, pad_to_len=pad_to_len) + prepared = self.loss_hooks.prepare(ctx, batch, pad_to_len=pad_to_len) train_pipeline_config = self.train_pipeline_config forward_dtype = self._forward_dtype @@ -587,19 +566,7 @@ def _compute_noise_pred(model) -> dict[str, torch.Tensor]: # PEFT re-enables adapter gradients on exit; reshard first so that lands on the shards, not gathered copies. reshard_model(prepared.model) - if self.custom_loss_formula_func is not None: - return self.custom_loss_formula_func( - ctx, - batch, - prepared, - new_pred=new_pred, - old_pred=old_pred, - ref_pred=ref_pred, - metrics=metrics, - write_old_log_prob=write_old_log_prob, - old_log_prob_from_new=old_log_prob_from_new, - ) - return flow_grpo_loss_formula( + return self.loss_hooks.formula( ctx, batch, prepared, diff --git a/miles/backends/fsdp_utils/loss_hub/__init__.py b/miles/backends/fsdp_utils/loss_hub/__init__.py index ac2f4b9a3..bbe51d5e5 100644 --- a/miles/backends/fsdp_utils/loss_hub/__init__.py +++ b/miles/backends/fsdp_utils/loss_hub/__init__.py @@ -1,11 +1,68 @@ -"""Diffusion batch preparation and loss hooks.""" +"""Diffusion batch preparation and loss hooks, selected by ``--loss-type`` and trainer role.""" +from __future__ import annotations + +from argparse import Namespace +from collections.abc import Callable +from dataclasses import dataclass +from typing import Any + +import torch + +from miles.backends.fsdp_utils.loss_hub.dmd2 import ( + critic_loss_formula, + dmd2_loss_formula, + prepare_critic_batch, + prepare_generator_batch, + score_last_step_samples, + select_scored_pairs, +) 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.sft import prepare_sft_batch, sft_loss_formula from miles.backends.fsdp_utils.loss_hub.types import DiffusionLossContext, PreparedBatch +from miles.utils.misc import load_function + +__all__ = ["LOSS_HOOKS", "DiffusionLossContext", "LossHooks", "PreparedBatch", "get_loss_hooks"] + + +@dataclass(frozen=True) +class LossHooks: + """The hooks one trainer group runs on a rollout. + + ``prepare`` builds a micro-batch's DiT inputs, ``formula`` turns the predictions into its loss, ``train_input`` + preprocesses the rank's train pairs before micro-batching, and ``train_output`` runs after the train steps and + hands its return value to the groups that train later. + """ + + prepare: Callable[..., PreparedBatch] + formula: Callable[..., torch.Tensor | None] + train_input: Callable[[DiffusionLossContext, list], list] | None = None + train_output: Callable[[DiffusionLossContext, list], Any] | None = None + + +LOSS_HOOKS: dict[tuple[str, str], LossHooks] = { + ("policy_loss", "actor"): LossHooks(prepare_flow_grpo_batch, flow_grpo_loss_formula), + ("nft", "actor"): LossHooks(prepare_nft_batch, nft_loss_formula), + ("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), +} + + +def get_loss_hooks(args: Namespace, role: str) -> LossHooks: + """The hooks of ``--loss-type`` for the trainer ``role``; only ``custom_loss`` reads the ``--custom-*-path`` flags. -__all__ = [ - "DiffusionLossContext", - "PreparedBatch", - "flow_grpo_loss_formula", - "prepare_flow_grpo_batch", -] + Under ``custom_loss`` an unset prepare or formula path falls back to Flow-GRPO's. + """ + if args.loss_type != "custom_loss": + return LOSS_HOOKS[(args.loss_type, role)] + flow_grpo_hooks = LOSS_HOOKS[("policy_loss", "actor")] + prepare = load_function(args.custom_prepare_train_batch_path) + formula = load_function(args.custom_loss_function_path) + return LossHooks( + prepare=flow_grpo_hooks.prepare if prepare is None else prepare, + formula=flow_grpo_hooks.formula if formula is None else formula, + train_input=load_function(args.custom_train_input_postprocess_path), + train_output=load_function(args.custom_train_output_function_path), + ) diff --git a/miles/rollout/sft_rollout.py b/miles/rollout/sft_rollout.py index 61abea7f8..ff5ee2dba 100644 --- a/miles/rollout/sft_rollout.py +++ b/miles/rollout/sft_rollout.py @@ -1,6 +1,6 @@ """SFT rollout plugin: lazy content-addressed encode cache behind the standard RolloutManager flow. -Plugged via --loss-type sft_loss (see set_default_diffusion_args): generate_rollout replaces the +Plugged via --loss-type sft_loss, whose recipes pass these three paths: generate_rollout replaces the sglang rollout, convert_samples_to_train_data replaces the reward/advantage conversion, and log_rollout_data replaces the reward logging. The encoder actor pool plays the architectural role sglang engines play in RL: the GPU data producer behind the rollout function, colocated on the diff --git a/miles/utils/arguments.py b/miles/utils/arguments.py index a95856749..740280fd0 100644 --- a/miles/utils/arguments.py +++ b/miles/utils/arguments.py @@ -947,10 +947,10 @@ def add_algo_arguments(parser): choices=["policy_loss", "sft_loss", "custom_loss", "nft", "dmd2"], default="policy_loss", help=( - "Train objective shortcut. Diffusion default policy_loss = Flow-GRPO prepare+formula. " - "nft auto-fills prepare / loss-formula paths and selects the NFT train-data converter. " - "dmd2 auto-fills the DMD2 converter / prepare / loss-formula / train-input paths and trains a " - "critic group before the actor. " + "Train objective. Each loss type selects its prepare / loss-formula / train-input / train-output " + "hooks from the loss hub by (loss_type, trainer role): policy_loss is Flow-GRPO; nft and dmd2 " + "also pick their default --custom-expand-samples-to-train-pairs-path, and dmd2 trains a critic " + "group before the actor. Only custom_loss reads the --custom-*-path hook flags. " "DiT forward always stays in the FSDP actor." ), ) @@ -961,7 +961,7 @@ def add_algo_arguments(parser): help=( "Dotted path to prepare hook " "`fn(ctx, batch, *, pad_to_len=None) -> PreparedBatch`. " - "Builds DiT inputs; default is Flow-GRPO SDE-pair stacking." + "Builds DiT inputs; --loss-type custom_loss only, default is Flow-GRPO SDE-pair stacking." ), ) parser.add_argument( @@ -971,6 +971,7 @@ def add_algo_arguments(parser): help=( "Dotted path to a loss *formula* only: " "`fn(ctx, batch, prepared, *, new_pred, ref_pred, metrics, ...) -> Tensor`. " + "--loss-type custom_loss only, default is Flow-GRPO's. " "DiT forward is owned by the actor; this hook only computes the objective." ), ) @@ -981,7 +982,8 @@ def add_algo_arguments(parser): help=( "Dotted path to `fn(ctx, train_pairs) -> list` that preprocesses this rank's train pairs (the " "converted rollout output) before they are split into micro-batches and optimizer steps. It " - "returns the pairs to train on; `ctx.external_data` holds earlier trainer groups' outputs." + "returns the pairs to train on; `ctx.external_data` holds earlier trainer groups' outputs. " + "--loss-type custom_loss only." ), ) parser.add_argument( @@ -991,7 +993,7 @@ def add_algo_arguments(parser): help=( "Dotted path to `fn(ctx, train_pairs) -> Any`, run without grad after the train steps of " "a rollout. Its return value reaches the paired rank of every trainer group that trains " - "later on the same rollout as `ctx.external_data[]`." + "later on the same rollout as `ctx.external_data[]`. --loss-type custom_loss only." ), ) parser.add_argument( @@ -1818,16 +1820,11 @@ def set_default_diffusion_args(args) -> None: if args.sglang_tp_size is None and args.sglang_sp_degree is None and not args.sglang_enable_cfg_parallel: args.sglang_tp_size = args.rollout_num_gpus_per_engine - is_nft = args.loss_type == "nft" - if is_nft: + if args.loss_type == "nft": if args.custom_expand_samples_to_train_pairs_path is None: args.custom_expand_samples_to_train_pairs_path = ( "miles.ray.data_conversion_hub.nft.expand_samples_to_train_pairs" ) - if args.custom_prepare_train_batch_path is None: - args.custom_prepare_train_batch_path = "miles.backends.fsdp_utils.loss_hub.nft.prepare_nft_batch" - if args.custom_loss_function_path is None: - args.custom_loss_function_path = "miles.backends.fsdp_utils.loss_hub.nft.nft_loss_formula" if args.loss_type == "dmd2": if args.custom_expand_samples_to_train_pairs_path is None: @@ -1838,12 +1835,6 @@ def set_default_diffusion_args(args) -> None: args.critic_load = args.teacher_load if args.critic_lr is None: args.critic_lr = args.lr - if args.custom_prepare_train_batch_path is None: - args.custom_prepare_train_batch_path = "miles.backends.fsdp_utils.loss_hub.dmd2.prepare_generator_batch" - if args.custom_loss_function_path is None: - args.custom_loss_function_path = "miles.backends.fsdp_utils.loss_hub.dmd2.dmd2_loss_formula" - if args.custom_train_input_postprocess_path is None: - args.custom_train_input_postprocess_path = "miles.backends.fsdp_utils.loss_hub.dmd2.select_scored_pairs" if args.ref_mode is None: args.ref_mode = "lora_base" if args.diffusion_kl_beta > 0 else "none" @@ -1894,15 +1885,6 @@ def validate_reference_model_args(args) -> None: raise ValueError("--ref-cpu-offload requires --ref-load") if args.teacher_cpu_offload and args.teacher_load is None: raise ValueError("--teacher-cpu-offload requires --teacher-load") - if ( - args.teacher_load is not None - and args.custom_prepare_train_batch_path is None - and args.custom_loss_function_path is None - and args.custom_train_output_function_path is None - ): - raise ValueError( - "--teacher-load has no consumer; only custom prepare/loss/train-output hooks read ctx.teacher_models" - ) if args.ref_mode == "lora_base" and not args.use_lora: raise ValueError("--ref-mode lora_base requires --use-lora") @@ -2002,13 +1984,31 @@ def validate_train_sde_backend(args) -> None: "--diffusion-log-prob-no-const with --diffusion-sde-type sde needs a --sde-step-backend-path " "whose log_prob also drops the constants" ) - # ODE rollouts carry zero log-probs and no noise; only a custom loss formula (NFT's is the default - # under --loss-type nft) can train on them, the Flow-GRPO one would score them as SDE steps. - if args.diffusion_sde_type == "ode" and args.custom_loss_function_path is None: - raise ValueError( - "--diffusion-sde-type ode is for DiffusionNFT (--loss-type nft) or a custom loss formula; " - "the Flow-GRPO loss needs an sde or cps rollout" - ) + # ODE rollouts carry zero log-probs and no noise, which the Flow-GRPO formula would score as SDE steps. + if args.diffusion_sde_type == "ode": + from miles.backends.fsdp_utils.loss_hub import LOSS_HOOKS, get_loss_hooks + + if get_loss_hooks(args, "actor").formula is LOSS_HOOKS[("policy_loss", "actor")].formula: + raise ValueError( + "--diffusion-sde-type ode is for DiffusionNFT (--loss-type nft), DMD2 or a custom loss formula; " + "the Flow-GRPO loss needs an sde or cps rollout" + ) + + +def validate_loss_hook_paths(args) -> None: + if args.loss_type == "custom_loss": + return + for name in ( + "custom_prepare_train_batch_path", + "custom_loss_function_path", + "custom_train_input_postprocess_path", + "custom_train_output_function_path", + ): + if getattr(args, name) is not None: + raise ValueError( + f"--{name.replace('_', '-')} is read only under --loss-type custom_loss; " + f"--loss-type {args.loss_type} selects its own hooks" + ) def validate_dmd2_args(args) -> None: @@ -2094,6 +2094,7 @@ def miles_validate_args(args): ) if len(set(args.update_weight_target_modules)) != len(args.update_weight_target_modules): raise ValueError(f"--update-weight-target-module has duplicates: {args.update_weight_target_module!r}") + validate_loss_hook_paths(args) validate_reference_model_args(args) validate_actor_lora_adapter(args) validate_score_centering_args(args) @@ -2181,12 +2182,7 @@ def miles_validate_args(args): "--loss-type sft_loss does not run rollout engines; pass " "--rollout-function-path miles.rollout.sft_rollout.generate_rollout (or your own)" ) - for name in ( - "custom_convert_samples_to_train_data_path", - "custom_rollout_log_function_path", - "custom_prepare_train_batch_path", - "custom_loss_function_path", - ): + for name in ("custom_convert_samples_to_train_data_path", "custom_rollout_log_function_path"): if getattr(args, name) is None: raise ValueError( f"--loss-type sft_loss requires --{name.replace('_', '-')}; " diff --git a/miles/utils/trainer_config.py b/miles/utils/trainer_config.py index 5066d56a9..7f51bea0d 100644 --- a/miles/utils/trainer_config.py +++ b/miles/utils/trainer_config.py @@ -24,10 +24,6 @@ def compute_trainer_configs(args: Namespace) -> list[TrainerConfig]: "global_batch_size": args.global_batch_size // critic_steps, # Only the actor's EMA has a reader (its weight sync); the critic's would be built, stepped and saved for nothing. "use_ema": False, - "custom_prepare_train_batch_path": "miles.backends.fsdp_utils.loss_hub.dmd2.prepare_critic_batch", - "custom_loss_function_path": "miles.backends.fsdp_utils.loss_hub.dmd2.critic_loss_formula", - "custom_train_input_postprocess_path": None, - "custom_train_output_function_path": "miles.backends.fsdp_utils.loss_hub.dmd2.score_last_step_samples", } return [ TrainerConfig(role="critic", overrides=critic_overrides), diff --git a/scripts/run_diffusion_sft_h3_ref2va.py b/scripts/run_diffusion_sft_h3_ref2va.py index 74b35108a..433552348 100644 --- a/scripts/run_diffusion_sft_h3_ref2va.py +++ b/scripts/run_diffusion_sft_h3_ref2va.py @@ -69,8 +69,6 @@ def execute(args: ScriptArgs) -> None: "--train-only " "--custom-convert-samples-to-train-data-path miles.rollout.sft_rollout.convert_samples_to_train_data " "--custom-rollout-log-function-path miles.rollout.sft_rollout.log_rollout_data " - "--custom-prepare-train-batch-path miles.backends.fsdp_utils.loss_hub.sft.prepare_sft_batch " - "--custom-loss-function-path miles.backends.fsdp_utils.loss_hub.sft.sft_loss_formula " "--diffusion-task ref2va " "--sft-offload-encoder " ) diff --git a/scripts/run_diffusion_sft_h3_t2va.py b/scripts/run_diffusion_sft_h3_t2va.py index b314f1f79..c9f713bd2 100644 --- a/scripts/run_diffusion_sft_h3_t2va.py +++ b/scripts/run_diffusion_sft_h3_t2va.py @@ -82,8 +82,6 @@ def execute(args: ScriptArgs) -> None: "--train-only " "--custom-convert-samples-to-train-data-path miles.rollout.sft_rollout.convert_samples_to_train_data " "--custom-rollout-log-function-path miles.rollout.sft_rollout.log_rollout_data " - "--custom-prepare-train-batch-path miles.backends.fsdp_utils.loss_hub.sft.prepare_sft_batch " - "--custom-loss-function-path miles.backends.fsdp_utils.loss_hub.sft.sft_loss_formula " "--sft-frame-stride 1 " "--sft-offload-encoder " ) diff --git a/scripts/run_diffusion_sft_wan22.py b/scripts/run_diffusion_sft_wan22.py index 4d6c9d305..843625674 100644 --- a/scripts/run_diffusion_sft_wan22.py +++ b/scripts/run_diffusion_sft_wan22.py @@ -71,8 +71,6 @@ def execute(args: ScriptArgs) -> None: "--train-only " "--custom-convert-samples-to-train-data-path miles.rollout.sft_rollout.convert_samples_to_train_data " "--custom-rollout-log-function-path miles.rollout.sft_rollout.log_rollout_data " - "--custom-prepare-train-batch-path miles.backends.fsdp_utils.loss_hub.sft.prepare_sft_batch " - "--custom-loss-function-path miles.backends.fsdp_utils.loss_hub.sft.sft_loss_formula " "--sft-frame-stride 2 " ) diff --git a/tests/fast/backends/fsdp_utils/test_loss_hub_nft.py b/tests/fast/backends/fsdp_utils/test_loss_hub_nft.py index acf1d16f3..c3e596099 100644 --- a/tests/fast/backends/fsdp_utils/test_loss_hub_nft.py +++ b/tests/fast/backends/fsdp_utils/test_loss_hub_nft.py @@ -42,8 +42,6 @@ def _args(**overrides): diffusion_nft_timestep_strategy_path="miles.ray.data_conversion_hub.nft.drop_final_steps", diffusion_nft_num_dropped_timesteps=0, seed=42, - custom_prepare_train_batch_path=None, - custom_loss_function_path=None, ) base.update(overrides) return Namespace(**base) diff --git a/tests/fast/backends/fsdp_utils/test_loss_hub_selection.py b/tests/fast/backends/fsdp_utils/test_loss_hub_selection.py new file mode 100644 index 000000000..f04403a15 --- /dev/null +++ b/tests/fast/backends/fsdp_utils/test_loss_hub_selection.py @@ -0,0 +1,116 @@ +"""--loss-type and the trainer role select a group's hooks from the loss hub; only custom_loss reads --custom-*-path. + + (loss_type, role) ──► LossHooks(prepare, formula, train_input, train_output) + policy_loss / actor Flow-GRPO prepare + formula, no input / output hook + nft / actor NFT prepare + formula + sft_loss / actor SFT prepare + formula + dmd2 / actor generator prepare + DMD2 formula, train_input = select_scored_pairs + dmd2 / critic critic prepare + critic formula, train_output = score_last_step_samples + custom_loss / actor each --custom-*-path loaded; unset prepare / formula fall back to Flow-GRPO's + no such (loss_type, role) ──► KeyError + +Each built-in entry is checked against the dotted path the argument defaults, the critic overrides or the SFT +recipes used to pass for it, so a hook moving to another function in the table is caught. +""" + +from tests.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=5, suite="stage-a-cpu", labels=[]) + +from argparse import Namespace + +import pytest + +from miles.backends.fsdp_utils.loss_hub import LOSS_HOOKS, LossHooks, get_loss_hooks +from miles.backends.fsdp_utils.loss_hub.flow_grpo import flow_grpo_loss_formula, prepare_flow_grpo_batch +from miles.utils.misc import function_registry, load_function + +HOOK_PATHS_BY_LOSS_TYPE_AND_ROLE = { + ("policy_loss", "actor"): dict( + prepare="miles.backends.fsdp_utils.loss_hub.flow_grpo.prepare_flow_grpo_batch", + formula="miles.backends.fsdp_utils.loss_hub.flow_grpo.flow_grpo_loss_formula", + ), + ("nft", "actor"): dict( + prepare="miles.backends.fsdp_utils.loss_hub.nft.prepare_nft_batch", + formula="miles.backends.fsdp_utils.loss_hub.nft.nft_loss_formula", + ), + ("sft_loss", "actor"): dict( + prepare="miles.backends.fsdp_utils.loss_hub.sft.prepare_sft_batch", + formula="miles.backends.fsdp_utils.loss_hub.sft.sft_loss_formula", + ), + ("dmd2", "actor"): dict( + prepare="miles.backends.fsdp_utils.loss_hub.dmd2.prepare_generator_batch", + formula="miles.backends.fsdp_utils.loss_hub.dmd2.dmd2_loss_formula", + train_input="miles.backends.fsdp_utils.loss_hub.dmd2.select_scored_pairs", + ), + ("dmd2", "critic"): dict( + prepare="miles.backends.fsdp_utils.loss_hub.dmd2.prepare_critic_batch", + formula="miles.backends.fsdp_utils.loss_hub.dmd2.critic_loss_formula", + train_output="miles.backends.fsdp_utils.loss_hub.dmd2.score_last_step_samples", + ), +} + + +def _custom_args(**paths): + unset = dict( + custom_prepare_train_batch_path=None, + custom_loss_function_path=None, + custom_train_input_postprocess_path=None, + custom_train_output_function_path=None, + ) + return Namespace(loss_type="custom_loss", **{**unset, **paths}) + + +@pytest.mark.parametrize(("loss_type", "role"), list(HOOK_PATHS_BY_LOSS_TYPE_AND_ROLE)) +def test_builtin_hooks_are_the_functions_the_paths_named(loss_type, role): + hooks = get_loss_hooks(Namespace(loss_type=loss_type), role) + + assert hooks is LOSS_HOOKS[(loss_type, role)] + paths = HOOK_PATHS_BY_LOSS_TYPE_AND_ROLE[(loss_type, role)] + assert hooks == LossHooks( + prepare=load_function(paths["prepare"]), + formula=load_function(paths["formula"]), + train_input=load_function(paths.get("train_input")), + train_output=load_function(paths.get("train_output")), + ) + + +def test_the_table_has_no_other_entries(): + assert set(LOSS_HOOKS) == set(HOOK_PATHS_BY_LOSS_TYPE_AND_ROLE) + + +def test_custom_loss_loads_every_path(): + def prepare(ctx, batch, *, pad_to_len=None): + pass + + def formula(ctx, batch, prepared, **kwargs): + pass + + def train_input(ctx, train_pairs): + pass + + def train_output(ctx, train_pairs): + pass + + args = _custom_args( + custom_prepare_train_batch_path="my.prepare", + custom_loss_function_path="my.formula", + custom_train_input_postprocess_path="my.train_input", + custom_train_output_function_path="my.train_output", + ) + with ( + function_registry.temporary("my.prepare", prepare), + function_registry.temporary("my.formula", formula), + function_registry.temporary("my.train_input", train_input), + function_registry.temporary("my.train_output", train_output), + ): + assert get_loss_hooks(args, "actor") == LossHooks(prepare, formula, train_input, train_output) + + +def test_custom_loss_falls_back_to_flow_grpo_for_unset_prepare_and_formula(): + assert get_loss_hooks(_custom_args(), "actor") == LossHooks(prepare_flow_grpo_batch, flow_grpo_loss_formula) + + +def test_a_role_without_hooks_for_the_loss_type_is_rejected(): + with pytest.raises(KeyError): + get_loss_hooks(Namespace(loss_type="nft"), "critic") diff --git a/tests/fast/backends/fsdp_utils/test_reference_models.py b/tests/fast/backends/fsdp_utils/test_reference_models.py index e6e5fe468..8f6f2ad99 100644 --- a/tests/fast/backends/fsdp_utils/test_reference_models.py +++ b/tests/fast/backends/fsdp_utils/test_reference_models.py @@ -171,8 +171,7 @@ def loss_formula(ctx, batch, prepared, *, new_pred, old_pred, ref_pred, **kwargs reference_models=reference_models, train_pipeline_config=TinyPipelineConfig(), _forward_dtype=torch.float32, - custom_prepare_train_batch_func=lambda *args, **kwargs: prepared, - custom_loss_formula_func=loss_formula, + loss_hooks=SimpleNamespace(prepare=lambda *args, **kwargs: prepared, formula=loss_formula), ) return harness, observed diff --git a/tests/fast/backends/fsdp_utils/test_train_input_hook.py b/tests/fast/backends/fsdp_utils/test_train_input_hook.py index 52b85f9b5..ee94596ff 100644 --- a/tests/fast/backends/fsdp_utils/test_train_input_hook.py +++ b/tests/fast/backends/fsdp_utils/test_train_input_hook.py @@ -69,8 +69,7 @@ def _actor(train_input, train_output, forwarded): ), _forward_dtype=torch.float32, parallel_state=SimpleNamespace(dp_rank=0, dp_group=None), - custom_train_input_postprocess_func=train_input, - custom_train_output_func=train_output, + loss_hooks=SimpleNamespace(train_input=train_input, train_output=train_output), optimizer=SimpleNamespace(zero_grad=lambda set_to_none: None), global_step=0, _maybe_legacy_window_pad_len=lambda train_pairs, microbatch_ranges: None, diff --git a/tests/fast/utils/test_dmd2_arguments.py b/tests/fast/utils/test_dmd2_arguments.py index 1009fe112..c4752cd9f 100644 --- a/tests/fast/utils/test_dmd2_arguments.py +++ b/tests/fast/utils/test_dmd2_arguments.py @@ -1,7 +1,7 @@ """--loss-type dmd2 defaults and validation; validation rejects what DMD2 cannot run and never fills args. - defaults ──► converter / generator prepare / generator loss / train-input paths, - --critic-load = --teacher-load, --critic-lr = --lr, unless the user set them + defaults ──► the expand path, --critic-load = --teacher-load, --critic-lr = --lr, unless the user + set them; no hook path: the loss hub selects the generator's and the critic's hooks by role critic group ──► scores with --teacher-load (no adapters), learns on a visual --fsdp-flow-shift grid, scores in a 0 <= MIN < MAX <= 1 --dmd2-score-sigma-range, takes --dmd2-critic-steps-per-rollout steps over each DP shard @@ -59,9 +59,6 @@ def test_dmd2_critic_defaults_to_the_teacher_and_the_actor_lr(user, expected): rollout_num_gpus_per_engine=1, loss_type="dmd2", custom_expand_samples_to_train_pairs_path=None, - custom_prepare_train_batch_path=None, - custom_loss_function_path=None, - custom_train_input_postprocess_path=None, ref_mode=None, diffusion_kl_beta=0.0, teacher_load="teacher", @@ -79,8 +76,7 @@ def test_critic_flags_without_dmd2_are_rejected(flag): validate_dmd2_args(Namespace(loss_type="nft", critic_load=None, critic_lr=None)) -@pytest.mark.parametrize("custom_loss", [None, "my.generator_loss"]) -def test_dmd2_fills_only_unset_hook_paths(custom_loss): +def test_dmd2_fills_the_expand_path_and_touches_no_hook_path(): args = Namespace( sglang_tp_size=1, sglang_sp_degree=None, @@ -88,9 +84,6 @@ def test_dmd2_fills_only_unset_hook_paths(custom_loss): rollout_num_gpus_per_engine=1, loss_type="dmd2", custom_expand_samples_to_train_pairs_path=None, - custom_prepare_train_batch_path=None, - custom_loss_function_path=custom_loss, - custom_train_input_postprocess_path=None, ref_mode=None, diffusion_kl_beta=0.0, teacher_load="teacher", @@ -98,16 +91,16 @@ def test_dmd2_fills_only_unset_hook_paths(custom_loss): critic_load=None, critic_lr=None, ) + original = vars(args).copy() set_default_diffusion_args(args) - assert args.custom_expand_samples_to_train_pairs_path.endswith( - "data_conversion_hub.dmd2.expand_samples_to_train_pairs" - ) - assert args.custom_prepare_train_batch_path.endswith("loss_hub.dmd2.prepare_generator_batch") - assert args.custom_loss_function_path == ( - custom_loss or "miles.backends.fsdp_utils.loss_hub.dmd2.dmd2_loss_formula" - ) - assert args.custom_train_input_postprocess_path.endswith("loss_hub.dmd2.select_scored_pairs") - assert args.ref_mode == "none" + # A Namespace without the hook path attributes: a default that wrote one would add a key here. + assert vars(args) == { + **original, + "custom_expand_samples_to_train_pairs_path": "miles.ray.data_conversion_hub.dmd2.expand_samples_to_train_pairs", + "critic_load": "teacher", + "critic_lr": 2e-6, + "ref_mode": "none", + } def test_valid_dmd2_args_pass_unchanged(): diff --git a/tests/fast/utils/test_loss_hook_path_args.py b/tests/fast/utils/test_loss_hook_path_args.py new file mode 100644 index 000000000..40c2137b6 --- /dev/null +++ b/tests/fast/utils/test_loss_hook_path_args.py @@ -0,0 +1,35 @@ +"""The --custom-*-path hook flags are read only under --loss-type custom_loss, so any other loss type rejects them.""" + +from tests.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=5, suite="stage-a-cpu", labels=[]) + +from argparse import Namespace + +import pytest + +from miles.utils.arguments import validate_loss_hook_paths + +HOOK_PATH_NAMES = ( + "custom_prepare_train_batch_path", + "custom_loss_function_path", + "custom_train_input_postprocess_path", + "custom_train_output_function_path", +) + + +def _args(loss_type, **paths): + return Namespace(loss_type=loss_type, **{**dict.fromkeys(HOOK_PATH_NAMES), **paths}) + + +@pytest.mark.parametrize("loss_type", ["policy_loss", "nft", "sft_loss", "dmd2"]) +@pytest.mark.parametrize("name", HOOK_PATH_NAMES) +def test_hook_paths_outside_custom_loss_are_rejected(loss_type, name): + with pytest.raises(ValueError, match=f"--{name.replace('_', '-')} is read only under --loss-type custom_loss"): + validate_loss_hook_paths(_args(loss_type, **{name: "my.hook"})) + validate_loss_hook_paths(_args(loss_type)) + + +def test_custom_loss_accepts_any_subset_of_hook_paths(): + validate_loss_hook_paths(_args("custom_loss", custom_loss_function_path="my.formula")) + validate_loss_hook_paths(_args("custom_loss")) diff --git a/tests/fast/utils/test_loss_type_recipes_parse.py b/tests/fast/utils/test_loss_type_recipes_parse.py new file mode 100644 index 000000000..cf8164ea8 --- /dev/null +++ b/tests/fast/utils/test_loss_type_recipes_parse.py @@ -0,0 +1,105 @@ +"""One representative command line per --loss-type parses, takes its defaults and passes validation. + + policy_loss Flow-GRPO SDE rollout + nft ODE rollout with --use-ema --rollout-weights ema + sft_loss --train-only with an external producer; the SFT prepare / loss hooks need no path + dmd2 --teacher-load, ODE rollout stopped at a random step; the critic group's and the actor's hooks + come from the loss hub by role, so the trainer args carry no hook path + +The arguments pass through load_fsdp_args, set_default_diffusion_args and miles_validate_args exactly as parse_args +runs them, so a validator that reads a value the defaults no longer fill fails here, not on the launch node. +""" + +from tests.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=10, suite="stage-a-cpu", labels=[]) + +import shlex +import sys +from argparse import Namespace + +import pytest + +from miles.backends.fsdp_utils.arguments import load_fsdp_args +from miles.backends.fsdp_utils.loss_hub import LOSS_HOOKS, get_loss_hooks +from miles.utils.arguments import get_miles_extra_args_provider, miles_validate_args, set_default_diffusion_args +from miles.utils.trainer_config import compute_trainer_args, compute_trainer_configs + +COMMON_ARGV = ( + "test --hf-checkpoint checkpoint --diffusion-model-family sd3 --diffusion-task t2i --prompt-data prompts.jsonl " + "--rollout-batch-size 4 --n-samples-per-prompt 2 --global-batch-size 8 --num-rollout 1 --num-steps-per-rollout 1 " + "--actor-num-gpus-per-node 2 --rollout-num-gpus 2 --rollout-num-gpus-per-engine 1 --micro-batch-size 1 " + "--rollout-function-path miles.rollout.sglang_diffusion_rollout.generate_rollout --rm-type pickscore " +) +ARGV_BY_LOSS_TYPE = { + "policy_loss": COMMON_ARGV + "--loss-type policy_loss --diffusion-sde-type sde", + "nft": COMMON_ARGV + + "--loss-type nft --diffusion-sde-type ode --diffusion-noise-level 0.0 --use-ema --rollout-weights ema", + "sft_loss": ( + "test --hf-checkpoint checkpoint --diffusion-model-family wan2_2 --diffusion-task t2v --train-only " + "--loss-type sft_loss --prompt-data dataset.yaml --rollout-function-path external.generate " + "--fsdp-flow-shift 5 --rollout-batch-size 1 --global-batch-size 1 --num-rollout 1 " + "--actor-num-gpus-per-node 1 --micro-batch-size 1 " + "--custom-convert-samples-to-train-data-path external.convert " + "--custom-rollout-log-function-path external.log" + ), + "dmd2": COMMON_ARGV + + "--loss-type dmd2 --teacher-load teacher --dmd2-teacher-guidance-scale 1.0 --dmd2-critic-steps-per-rollout 2 " + "--fsdp-flow-shift visual=3.0 --diffusion-sde-type ode --diffusion-guidance-scale 1.0 --rm-type none " + "--diffusion-step-strategy-path miles.rollout.step_strategy_hub.stop_at_random_step", +} + + +@pytest.fixture +def parse(monkeypatch: pytest.MonkeyPatch): + from miles.backends.fsdp_utils.configs import train_pipeline_config + + class _FakePipelineConfig: + model_backend_path = "external.Backend" + supports_cfg_training = True + tasks = ("t2i", "t2v") + + @classmethod + def validate_args(cls, args: Namespace) -> None: + pass + + monkeypatch.setattr(train_pipeline_config, "get_train_pipeline_config_cls", lambda family: _FakePipelineConfig) + + def run(argv: str) -> Namespace: + monkeypatch.setattr(sys, "argv", shlex.split(argv)) + args = load_fsdp_args(extra_args_provider=get_miles_extra_args_provider()) + set_default_diffusion_args(args) + miles_validate_args(args) + return args + + return run + + +@pytest.mark.parametrize("loss_type", list(ARGV_BY_LOSS_TYPE)) +def test_each_loss_type_recipe_parses_and_validates(parse, loss_type): + args = parse(ARGV_BY_LOSS_TYPE[loss_type]) + assert args.loss_type == loss_type + + +def test_dmd2_trainer_groups_get_their_hooks_by_role(parse): + args = parse(ARGV_BY_LOSS_TYPE["dmd2"]) + + critic_config, actor_config = compute_trainer_configs(args) + critic = compute_trainer_args(args, critic_config) + actor = compute_trainer_args(args, actor_config) + + assert get_loss_hooks(critic, critic_config.role) is LOSS_HOOKS[("dmd2", "critic")] + assert get_loss_hooks(actor, actor_config.role) is LOSS_HOOKS[("dmd2", "actor")] + # No hook path in the parsed args: the overrides are the whole critic / actor difference. + assert vars(critic) == { + **vars(args), + "hf_checkpoint": "teacher", + "num_steps_per_rollout": 2, + "global_batch_size": 4, + } + assert vars(actor) == {**vars(args), "teacher_load": None} + + +def test_a_hook_path_outside_custom_loss_fails_validation(parse): + with pytest.raises(ValueError, match="read only under --loss-type custom_loss"): + parse(ARGV_BY_LOSS_TYPE["nft"] + " --teacher-load teacher --custom-loss-function-path my.formula") diff --git a/tests/fast/utils/test_reference_arguments.py b/tests/fast/utils/test_reference_arguments.py index 04646fde4..890b55844 100644 --- a/tests/fast/utils/test_reference_arguments.py +++ b/tests/fast/utils/test_reference_arguments.py @@ -2,7 +2,7 @@ actor: full / LoRA ---> ref: base / base + LoRA, teacher: base / base + LoRA actor: LoRA ---> lora_base: reuse actor with its adapter disabled - teacher ---> read only by custom prepare/loss hooks, so it needs one + teacher ---> loaded for whichever hook reads ctx.teacher_models; nothing in args says who will actor LoRA enabled --> adapter config --> checkpoint A/B support + uniform IPC scaling + CLI r/alpha match adapter paths ---> one plain PEFT directory per component, in order; any other count is rejected @@ -65,17 +65,12 @@ def test_frozen_models_do_not_inherit_actor_training_mode(use_lora, role_has_ada teacher_lora_adapter_paths=["teacher-high", "teacher-low"] if role_has_adapter else None, ref_cpu_offload=True, teacher_cpu_offload=True, - custom_loss_function_path="my_loss.teacher_loss", ) original = vars(args).copy() validate_reference_model_args(args) assert vars(args) == original -def test_train_output_hook_consumes_the_teacher(): - validate_reference_model_args(_args(teacher_load="teacher", custom_train_output_function_path="my_hook.score")) - - def test_lora_base_needs_no_separate_reference_checkpoint(): args = _args(use_lora=True, lora_adapter_paths=["actor-high", "actor-low"], ref_mode="lora_base") validate_reference_model_args(args) @@ -97,7 +92,6 @@ def test_lora_base_needs_no_separate_reference_checkpoint(): ({"ref_cpu_offload": True}, "--ref-cpu-offload requires --ref-load"), ({"teacher_cpu_offload": True}, "--teacher-cpu-offload requires --teacher-load"), ({"ref_mode": "lora_base"}, "--ref-mode lora_base requires --use-lora"), - ({"teacher_load": "teacher"}, "--teacher-load has no consumer"), ], ) def test_incomplete_model_roles_are_rejected(overrides, message): diff --git a/tests/fast/utils/test_sft_encoder_args.py b/tests/fast/utils/test_sft_encoder_args.py index a78170b1e..ab2120336 100644 --- a/tests/fast/utils/test_sft_encoder_args.py +++ b/tests/fast/utils/test_sft_encoder_args.py @@ -1,5 +1,13 @@ -"""SFT argument validation: encoder requirements apply only to the built-in producer; flow shifts and supervised -streams are named per stream.""" +"""SFT argument validation. + + --loss-type sft_loss ──► requires the convert and rollout-log paths; its prepare / loss hooks come from the + loss hub, so a --custom-prepare-train-batch-path is rejected + producer built-in ──► --sft-encoder-checkpoint required, encoder validates its args + external ──► no encoder requirement + --fsdp-flow-shift "5" is the visual shift, "visual=12,audio=3" keys each stream; visual required, > 0 + --fsdp-supervised-streams comma-separated, visual required, only visual / audio known + --diffusion-task must be one of the config's tasks +""" import shlex import sys @@ -46,8 +54,7 @@ def validate_args(cls, args: Namespace) -> None: "--rollout-batch-size 1 --global-batch-size 1 --num-rollout 1 " "--actor-num-gpus-per-node 1 --micro-batch-size 1 " "--custom-convert-samples-to-train-data-path external.convert " - "--custom-rollout-log-function-path external.log " - "--custom-prepare-train-batch-path external.prepare --custom-loss-function-path external.loss" + "--custom-rollout-log-function-path external.log" ), ) result = load_fsdp_args(extra_args_provider=get_miles_extra_args_provider()) @@ -101,7 +108,14 @@ def test_builtin_producer_still_requires_checkpoint(args: Namespace) -> None: miles_validate_args(args) -def test_external_producer_still_requires_sft_hooks(args: Namespace) -> None: - args.custom_prepare_train_batch_path = None - with pytest.raises(ValueError, match="custom-prepare-train-batch-path"): +def test_sft_loss_rejects_a_prepare_path(args: Namespace) -> None: + # The SFT hooks come from the loss hub; a path would be a second, possibly different, source. + args.custom_prepare_train_batch_path = "external.prepare" + with pytest.raises(ValueError, match="read only under --loss-type custom_loss"): + miles_validate_args(args) + + +def test_external_producer_still_requires_the_convert_hook(args: Namespace) -> None: + args.custom_convert_samples_to_train_data_path = None + with pytest.raises(ValueError, match="custom-convert-samples-to-train-data-path"): miles_validate_args(args) diff --git a/tests/fast/utils/test_sglang_parallel_defaults.py b/tests/fast/utils/test_sglang_parallel_defaults.py index 6aea3456a..8d28f8fe4 100644 --- a/tests/fast/utils/test_sglang_parallel_defaults.py +++ b/tests/fast/utils/test_sglang_parallel_defaults.py @@ -29,8 +29,6 @@ def _args(**overrides): rollout_num_gpus_per_engine=4, loss_type="grpo", custom_expand_samples_to_train_pairs_path=None, - custom_prepare_train_batch_path=None, - custom_loss_function_path=None, ref_mode="none", diffusion_kl_beta=0.0, ) diff --git a/tests/fast/utils/test_train_sde_backend_args.py b/tests/fast/utils/test_train_sde_backend_args.py index 6466359da..9c3aa44c5 100644 --- a/tests/fast/utils/test_train_sde_backend_args.py +++ b/tests/fast/utils/test_train_sde_backend_args.py @@ -2,8 +2,8 @@ sde + no-const + default FlowSdeStepBackend (keeps constants) --> rejected sde + no-const + custom --sde-step-backend-path --> allowed (backend owns it) - ode + Flow-GRPO loss formula (no custom formula) --> rejected - ode + NFT / custom loss formula; cps; flag off --> allowed + ode + the Flow-GRPO formula (policy_loss, or custom_loss without a formula path) --> rejected + ode + nft / dmd2 / custom_loss with its own formula; cps; flag off --> allowed """ from tests.ci.ci_register import register_cpu_ci @@ -24,7 +24,11 @@ def _args(**overrides): diffusion_log_prob_no_const=True, diffusion_sde_type="sde", sde_step_backend_path=None, + loss_type="policy_loss", + custom_prepare_train_batch_path=None, custom_loss_function_path=None, + custom_train_input_postprocess_path=None, + custom_train_output_function_path=None, ) values.update(overrides) return Namespace(**values) @@ -35,6 +39,7 @@ def _args(**overrides): [ (dict(), "--diffusion-log-prob-no-const"), (dict(diffusion_sde_type="ode"), "--diffusion-sde-type ode"), + (dict(diffusion_sde_type="ode", loss_type="custom_loss"), "--diffusion-sde-type ode"), ], ) def test_rejects_rollouts_the_backend_cannot_score(overrides, match): @@ -47,7 +52,9 @@ def test_rejects_rollouts_the_backend_cannot_score(overrides, match): [ dict(sde_step_backend_path="my_pkg.backends.NoConstFlowSde"), dict(diffusion_sde_type="cps"), - dict(diffusion_sde_type="ode", custom_loss_function_path=NFT_FORMULA), + dict(diffusion_sde_type="ode", loss_type="nft"), + dict(diffusion_sde_type="ode", loss_type="dmd2"), + dict(diffusion_sde_type="ode", loss_type="custom_loss", custom_loss_function_path=NFT_FORMULA), dict(diffusion_log_prob_no_const=False), ], ) diff --git a/tests/fast/utils/test_trainer_config.py b/tests/fast/utils/test_trainer_config.py index 9bc4108dc..8834e8dd2 100644 --- a/tests/fast/utils/test_trainer_config.py +++ b/tests/fast/utils/test_trainer_config.py @@ -46,10 +46,6 @@ def test_dmd2_critic_trains_first_from_its_own_checkpoint(load, save, critic_dir num_steps_per_rollout=1, dmd2_critic_steps_per_rollout=5, use_ema=True, - custom_prepare_train_batch_path="my.prepare_generator", - custom_loss_function_path="my.generator_loss", - custom_train_input_postprocess_path="my.select_pairs", - custom_train_output_function_path=None, ) original = vars(args).copy() @@ -57,13 +53,17 @@ def test_dmd2_critic_trains_first_from_its_own_checkpoint(load, save, critic_dir assert [config.role for config in trainer_configs] == ["critic", "actor"] critic, actor = (compute_trainer_args(args, config) for config in trainer_configs) - assert (critic.hf_checkpoint, critic.teacher_load, critic.lr) == ("critic-init", "teacher", 8e-6) - assert (critic.load, critic.save) == (critic_dir, critic_dir) - assert (critic.num_steps_per_rollout, critic.global_batch_size) == (5, 8) - assert (critic.use_ema, actor.use_ema) == (False, True) - assert critic.custom_prepare_train_batch_path.endswith("loss_hub.dmd2.prepare_critic_batch") - assert critic.custom_loss_function_path.endswith("loss_hub.dmd2.critic_loss_formula") - assert critic.custom_train_input_postprocess_path is None - assert critic.custom_train_output_function_path.endswith("loss_hub.dmd2.score_last_step_samples") + # The critic differs from the run's args only in what it trains, how fast, where it checkpoints, how many + # steps it takes and that it keeps no EMA; its hooks come from the loss hub by role, not from args. + assert vars(critic) == { + **original, + "hf_checkpoint": "critic-init", + "lr": 8e-6, + "load": critic_dir, + "save": critic_dir, + "num_steps_per_rollout": 5, + "global_batch_size": 8, + "use_ema": False, + } assert vars(actor) == {**original, "teacher_load": None} assert vars(args) == original