From 66100f7642beafa46545b98f3a5d33b5ad592e3a Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Mon, 19 Oct 2026 20:06:46 +0000 Subject: [PATCH 01/33] feat(ray): hand earlier trainer groups' outputs to later groups as external_data --- docs/user-guide/cli-reference.md | 3 ++- docs/user-guide/customization.md | 12 +++++++++++ miles/backends/fsdp_utils/actor.py | 21 ++++++++++++++++--- miles/backends/fsdp_utils/loss_hub/types.py | 1 + miles/ray/actor_group.py | 12 ++++++++--- miles/ray/train_actor.py | 2 +- miles/utils/arguments.py | 15 ++++++++++++- .../backends/fsdp_utils/test_ema_optimizer.py | 4 +++- tests/fast/rollout/test_async_training.py | 4 ++-- tests/fast/rollout/test_placement_group.py | 18 ++++++++++++++++ tests/fast/test_train_diffusion.py | 13 +++++++----- tests/fast/utils/test_reference_arguments.py | 5 +++++ train_diffusion.py | 4 +++- 13 files changed, 96 insertions(+), 18 deletions(-) diff --git a/docs/user-guide/cli-reference.md b/docs/user-guide/cli-reference.md index 655440a70..d46290c60 100644 --- a/docs/user-guide/cli-reference.md +++ b/docs/user-guide/cli-reference.md @@ -273,11 +273,12 @@ 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 hooks as `ctx.teacher_models`, so it requires `--custom-prepare-train-batch-path` or `--custom-loss-function-path`. | +| `--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-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-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[]`. | | `--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 ef5ceb32a..88fa86b64 100644 --- a/docs/user-guide/customization.md +++ b/docs/user-guide/customization.md @@ -25,6 +25,7 @@ signatures they expect, and the defaults they replace — in the same spirit as | | `--custom-convert-samples-to-train-data-path` | Full sample → train_data | | | `--custom-prepare-train-batch-path` | DiT batch preparation | | | `--custom-loss-function-path` | Loss formula only | +| | `--custom-train-output-function-path` | Output handed to later trainer groups | | | `--sde-step-backend-path` | Train-side SDE dynamics | | **Logging** | `--custom-rollout-log-function-path` | Train-rollout logging | | | `--custom-eval-rollout-log-function-path` | Eval-rollout logging | @@ -282,6 +283,17 @@ 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`. +### `--custom-train-output-function-path` + +```python +def train_output(ctx, train_pairs) -> Any: + ... +``` + +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[]`. + ### `--sde-step-backend-path` **Class** implementing `SdeStepBackend`. Auto-selected from diff --git a/miles/backends/fsdp_utils/actor.py b/miles/backends/fsdp_utils/actor.py index 1b3141e34..d5ab755f1 100644 --- a/miles/backends/fsdp_utils/actor.py +++ b/miles/backends/fsdp_utils/actor.py @@ -1,6 +1,7 @@ import logging from argparse import Namespace from contextlib import nullcontext +from typing import Any import ray import torch @@ -175,6 +176,11 @@ def init(self, args: Namespace, role: str, with_ref: bool = False) -> int: # ty 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_output_func = ( + load_function(args.custom_train_output_function_path) + if args.custom_train_output_function_path is not None + else None + ) if args.optimizer == "adam": self.optimizer = torch.optim.AdamW( @@ -323,7 +329,7 @@ def _log_metrics(self, rollout_id: int, log_dict: dict[str, float], step: int) - ) ) - def train(self, rollout_id: int, rollout_data_ref) -> None: # type: ignore[override] + def train(self, rollout_id: int, rollout_data_ref, external_data) -> Any: # type: ignore[override] if self.args.offload_train: self.wake_up() @@ -333,7 +339,10 @@ def train(self, rollout_id: int, rollout_data_ref) -> None: # type: ignore[over return if self.args.use_output_store: materialize_stored_tensors(rollout_data["train_data"], store=self._output_store) - self._train_core(rollout_id=rollout_id, rollout_data=rollout_data) + external_data = dict(zip(external_data, ray.get(list(external_data.values())), strict=True)) + train_output = self._train_core( + rollout_id=rollout_id, rollout_data=rollout_data, external_data=external_data + ) if self.ema_optimizer is not None: self.ema_optimizer.step(self.global_step) @@ -342,8 +351,9 @@ def train(self, rollout_id: int, rollout_data_ref) -> None: # type: ignore[over args=self.args, is_primary_rank=dist.get_rank() == 0, ) + return train_output - def _train_core(self, rollout_id: int, rollout_data) -> None: + def _train_core(self, rollout_id: int, rollout_data, external_data: dict[str, Any]) -> Any: """Run the shared diffusion training loop.""" device = torch.device("cuda", torch.cuda.current_device()) @@ -389,6 +399,7 @@ def _train_core(self, rollout_id: int, rollout_data) -> None: device=device, rollout_id=rollout_id, dp_rank=self.parallel_state.dp_rank, + external_data=external_data, ) # ------------- Recompute old log-probs (impl-consistent PPO ratio) ------------- @@ -471,6 +482,10 @@ def _train_core(self, rollout_id: int, rollout_data) -> None: reduced = {f"train/{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: + with torch.no_grad(): + return self.custom_train_output_func(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 None unless the legacy --micro-batch-size-sample>1 path is active. TODO: remove with it.""" diff --git a/miles/backends/fsdp_utils/loss_hub/types.py b/miles/backends/fsdp_utils/loss_hub/types.py index 2766effed..2d41b3537 100644 --- a/miles/backends/fsdp_utils/loss_hub/types.py +++ b/miles/backends/fsdp_utils/loss_hub/types.py @@ -25,6 +25,7 @@ class DiffusionLossContext: dp_rank: int = 0 reference_models: dict[str, torch.nn.Module] = field(default_factory=dict) teacher_models: dict[str, torch.nn.Module] = field(default_factory=dict) + external_data: dict[str, Any] = field(default_factory=dict) @dataclass(frozen=True) diff --git a/miles/ray/actor_group.py b/miles/ray/actor_group.py index f36a1ef70..3cb749b3f 100644 --- a/miles/ray/actor_group.py +++ b/miles/ray/actor_group.py @@ -100,9 +100,15 @@ def async_init(self, args, role, with_ref=False): self.args = args return [actor.init.remote(args, role, with_ref=with_ref) for actor in self._actor_handlers] - def async_train(self, rollout_id, rollout_data_ref): - """Do one rollout training""" - return [actor.train.remote(rollout_id, rollout_data_ref) for actor in self._actor_handlers] + def async_train(self, rollout_id, rollout_data_ref, external_data=None): + """Do one rollout training; rank i receives rank i's output of each group in ``external_data``.""" + external_data = external_data or {} + return [ + actor.train.remote( + rollout_id, rollout_data_ref, {role: refs[rank] for role, refs in external_data.items()} + ) + for rank, actor in enumerate(self._actor_handlers) + ] def save_model(self, rollout_id, force_sync=False): """Save actor model""" diff --git a/miles/ray/train_actor.py b/miles/ray/train_actor.py index bd5e7f889..18aa97a5c 100644 --- a/miles/ray/train_actor.py +++ b/miles/ray/train_actor.py @@ -122,7 +122,7 @@ def wake_up(self, tags): raise NotImplementedError @abc.abstractmethod - def train(self, rollout_id, rollout_data_ref): + def train(self, rollout_id, rollout_data_ref, external_data): raise NotImplementedError @abc.abstractmethod diff --git a/miles/utils/arguments.py b/miles/utils/arguments.py index 698642165..eafaf5fd8 100644 --- a/miles/utils/arguments.py +++ b/miles/utils/arguments.py @@ -971,6 +971,16 @@ def add_algo_arguments(parser): "DiT forward is owned by the actor; this hook only computes the objective." ), ) + parser.add_argument( + "--custom-train-output-function-path", + type=str, + default=None, + 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[]`." + ), + ) parser.add_argument( "--diffusion-nft-beta", type=float, @@ -1798,8 +1808,11 @@ def validate_reference_model_args(args) -> None: 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 hooks read ctx.teacher_models") + 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") diff --git a/tests/fast/backends/fsdp_utils/test_ema_optimizer.py b/tests/fast/backends/fsdp_utils/test_ema_optimizer.py index 21a4dabcb..4e4f67b4c 100644 --- a/tests/fast/backends/fsdp_utils/test_ema_optimizer.py +++ b/tests/fast/backends/fsdp_utils/test_ema_optimizer.py @@ -21,6 +21,7 @@ from contextlib import nullcontext from pathlib import Path from types import SimpleNamespace +from typing import Any import pytest import torch @@ -146,6 +147,7 @@ def test_actor_train_updates_ema_once_and_publication_only_reads_it(): for method in methods: method.decorator_list = [] namespace = dict( + Any=Any, ray=SimpleNamespace(get=lambda value: value), dist=SimpleNamespace(get_rank=lambda: 0), timer=lambda name: nullcontext(), @@ -181,7 +183,7 @@ def train_core(**kwargs): rollout_manager=SimpleNamespace(get_rollout_engines_and_lock=SimpleNamespace(remote=lambda: (None, None, 0))), weight_updater=SimpleNamespace(update_weights=lambda: published_weights.append(model.base.detach().clone())), ) - namespace["train"](actor, rollout_id=0, rollout_data_ref=[SimpleNamespace(inner={})]) + namespace["train"](actor, rollout_id=0, rollout_data_ref=[SimpleNamespace(inner={})], external_data={}) assert model.base.item() == 4.0 assert actor.ema_optimizer.state[model.base]["ema"].item() == 3.0 diff --git a/tests/fast/rollout/test_async_training.py b/tests/fast/rollout/test_async_training.py index abf2995b9..2923dd63d 100644 --- a/tests/fast/rollout/test_async_training.py +++ b/tests/fast/rollout/test_async_training.py @@ -94,7 +94,7 @@ def update_weights(self, previous_ema=False): self.actor.FSDPTrainRayActor.update_weights(self, previous_ema=previous_ema) return self.published, self.global_step - def _train_core(self, rollout_id, rollout_data): + def _train_core(self, rollout_id, rollout_data, external_data): start = time.monotonic() with self.ema_optimizer.use_weights(self.model): reference = self.param.item() @@ -109,7 +109,7 @@ def train(self, rollout_id, batch): with patch.object(self.actor.dist, "get_rank", return_value=0), patch.object( self.actor.train_metric_utils, "log_perf_data_raw" ): - self.actor.FSDPTrainRayActor.train(self, rollout_id, batch) + self.actor.FSDPTrainRayActor.train(self, rollout_id, batch, {}) def save_model(self, rollout_id, force_sync=False): from copy import deepcopy diff --git a/tests/fast/rollout/test_placement_group.py b/tests/fast/rollout/test_placement_group.py index 888443a83..5e1e0cdb6 100644 --- a/tests/fast/rollout/test_placement_group.py +++ b/tests/fast/rollout/test_placement_group.py @@ -3,10 +3,12 @@ register_cpu_ci(est_time=5, suite="stage-a-cpu", labels=[]) from argparse import Namespace +from types import SimpleNamespace import pytest import miles.ray.placement_group as placement_module +from miles.ray.actor_group import RayTrainGroup from miles.ray.utils import TRAIN_ACTOR_GPU from miles.utils.trainer_config import TrainerConfig @@ -107,3 +109,19 @@ def test_trainer_groups_split_the_train_gpu_share(monkeypatch, roles): def test_trainers_restored_to_different_rollouts_are_rejected(monkeypatch): with pytest.raises(AssertionError, match="trainers restored different rollouts"): _create_training_models(monkeypatch, {"critic": 2, "actor": 3}) + + +def test_each_rank_receives_the_same_rank_output_of_earlier_groups(): + class _Handle: + def __init__(self, rank): + self.train = SimpleNamespace(remote=lambda *args: (rank, *args)) + + group = object.__new__(RayTrainGroup) + group._actor_handlers = [_Handle(rank) for rank in range(2)] + external_data = {"critic": ["critic_0", "critic_1"], "reward": ["reward_0", "reward_1"]} + + assert group.async_train(7, "data", external_data) == [ + (0, 7, "data", {"critic": "critic_0", "reward": "reward_0"}), + (1, 7, "data", {"critic": "critic_1", "reward": "reward_1"}), + ] + assert group.async_train(7, "data") == [(0, 7, "data", {}), (1, 7, "data", {})] diff --git a/tests/fast/test_train_diffusion.py b/tests/fast/test_train_diffusion.py index 07cfdfa52..ab6ab3a6b 100644 --- a/tests/fast/test_train_diffusion.py +++ b/tests/fast/test_train_diffusion.py @@ -1,4 +1,5 @@ -"""train_diffusion.py trains every trainer group on each rollout in declared order, then releases the rollout.""" +"""train_diffusion.py trains every trainer group on each rollout in declared order, handing each the earlier +outputs, then releases the rollout.""" from tests.ci.ci_register import register_cpu_ci @@ -32,8 +33,9 @@ def __init__(self, role, events): self._role = role self._events = events - def async_train(self, rollout_id, rollout_data_ref): - self._events.append(("train_start", self._role, rollout_id, rollout_data_ref)) + def async_train(self, rollout_id, rollout_data_ref, external_data): + received = {role: [(ref.role, ref.rollout_id) for ref in refs] for role, refs in external_data.items()} + self._events.append(("train_start", self._role, rollout_id, rollout_data_ref, received)) return [_Ref(self._role, rollout_id)] def save_model(self, rollout_id, force_sync=False): @@ -86,9 +88,10 @@ def test_every_trainer_group_trains_each_rollout_in_order(monkeypatch): expected = [("update_weights", "actor")] for rollout_id in range(2): - for role in roles: + for i, role in enumerate(roles): + received = {earlier: [(earlier, rollout_id)] for earlier in roles[:i]} expected += [ - ("train_start", role, rollout_id, ("rollout_data", rollout_id)), + ("train_start", role, rollout_id, ("rollout_data", rollout_id), received), ("train_done", role, rollout_id), ] expected += [("release", rollout_id)] diff --git a/tests/fast/utils/test_reference_arguments.py b/tests/fast/utils/test_reference_arguments.py index ca8d47dfb..04646fde4 100644 --- a/tests/fast/utils/test_reference_arguments.py +++ b/tests/fast/utils/test_reference_arguments.py @@ -46,6 +46,7 @@ def _args(**overrides): diffusion_kl_beta=0.0, custom_prepare_train_batch_path=None, custom_loss_function_path=None, + custom_train_output_function_path=None, ) values.update(overrides) return Namespace(**values) @@ -71,6 +72,10 @@ def test_frozen_models_do_not_inherit_actor_training_mode(use_lora, role_has_ada 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) diff --git a/train_diffusion.py b/train_diffusion.py index 716fc359e..b4075788f 100644 --- a/train_diffusion.py +++ b/train_diffusion.py @@ -70,9 +70,11 @@ def save(rollout_id): if args.offload_rollout: ray.get(rollout_manager.offload.remote()) + train_outputs = {} for role, train_group in train_groups.items(): logger.info(f"train: rollout {rollout_id} {role} train start") - ray.get(train_group.async_train(rollout_id, rollout_data_ref)) + train_outputs[role] = train_group.async_train(rollout_id, rollout_data_ref, train_outputs) + ray.get(train_outputs[role]) logger.info(f"train: rollout {rollout_id} {role} train done") ray.get(rollout_manager.release.remote(rollout_id)) From 459222ddf48a3c4ed1e2478bc32779743cae6cd8 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Mon, 9 Nov 2026 22:06:19 +0000 Subject: [PATCH 02/33] fix(fsdp): box the train output so the driver's ray.get only waits `train` returned its train output directly, so the driver's ray.get on the train refs pulled every rank's output into the controller before the next group read it again from the object store. Return `Box(ray.put(output))` like the rollout shards: the driver gets a small box, the payload stays in the store until the paired rank of a later group unboxes it. Also note the train-output hook as a `--teacher-load` consumer in docs/fsdp_model_roles.md, which cli-reference.md already did. Co-Authored-By: Claude Mythos 5.1 --- docs/fsdp_model_roles.md | 5 +- miles/backends/fsdp_utils/actor.py | 7 +- .../backends/fsdp_utils/test_ema_optimizer.py | 4 +- .../fsdp_utils/test_train_output_handoff.py | 67 +++++++++++++++++++ 4 files changed, 78 insertions(+), 5 deletions(-) create mode 100644 tests/fast/backends/fsdp_utils/test_train_output_handoff.py diff --git a/docs/fsdp_model_roles.md b/docs/fsdp_model_roles.md index 4c749d6df..74db273c4 100644 --- a/docs/fsdp_model_roles.md +++ b/docs/fsdp_model_roles.md @@ -37,8 +37,9 @@ access `ctx.reference_models` by component name. A third source, the teacher (`--teacher-load`, with `--teacher-lora-adapter-path` for its adapters), is reserved for a DMD2-style loss that miles does not ship yet. Until then it -has no built-in consumer: `--teacher-load` requires a custom prepare/loss hook, which reads -it from `ctx.teacher_models`, and teacher inference should run inside `torch.no_grad()`. +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()`. 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/miles/backends/fsdp_utils/actor.py b/miles/backends/fsdp_utils/actor.py index d5ab755f1..55858aba7 100644 --- a/miles/backends/fsdp_utils/actor.py +++ b/miles/backends/fsdp_utils/actor.py @@ -20,6 +20,7 @@ from miles.utils.metric_buffer import MetricBuffer from miles.utils.metric_utils import compute_rollout_step from miles.utils.output_store import connect_output_store, materialize_stored_tensors, mooncake_client +from miles.utils.ray_utils import Box from miles.utils.timer import Timer, inverse_timer, timer from miles.utils.tracking_utils import init_tracking from miles.utils.train_data_utils import ( @@ -339,7 +340,7 @@ def train(self, rollout_id: int, rollout_data_ref, external_data) -> Any: # typ return if self.args.use_output_store: materialize_stored_tensors(rollout_data["train_data"], store=self._output_store) - external_data = dict(zip(external_data, ray.get(list(external_data.values())), strict=True)) + external_data = {role: ray.get(box.inner) for role, box in external_data.items()} train_output = self._train_core( rollout_id=rollout_id, rollout_data=rollout_data, external_data=external_data ) @@ -351,7 +352,9 @@ def train(self, rollout_id: int, rollout_data_ref, external_data) -> Any: # typ args=self.args, is_primary_rank=dist.get_rank() == 0, ) - return train_output + # Boxed like the rollout shards: the driver's ray.get on this task only waits, the payload stays in the + # object store until the paired rank of a later group reads it. + return Box(ray.put(train_output)) def _train_core(self, rollout_id: int, rollout_data, external_data: dict[str, Any]) -> Any: """Run the shared diffusion training loop.""" diff --git a/tests/fast/backends/fsdp_utils/test_ema_optimizer.py b/tests/fast/backends/fsdp_utils/test_ema_optimizer.py index 4e4f67b4c..dcb7596c7 100644 --- a/tests/fast/backends/fsdp_utils/test_ema_optimizer.py +++ b/tests/fast/backends/fsdp_utils/test_ema_optimizer.py @@ -30,6 +30,7 @@ from miles.backends.fsdp_utils import checkpoint from miles.backends.fsdp_utils.ema import EMAOptimizer +from miles.utils.ray_utils import Box class Model(nn.Module): @@ -148,7 +149,8 @@ def test_actor_train_updates_ema_once_and_publication_only_reads_it(): method.decorator_list = [] namespace = dict( Any=Any, - ray=SimpleNamespace(get=lambda value: value), + Box=Box, + ray=SimpleNamespace(get=lambda value: value, put=lambda value: value), dist=SimpleNamespace(get_rank=lambda: 0), timer=lambda name: nullcontext(), inverse_timer=lambda name: nullcontext(), diff --git a/tests/fast/backends/fsdp_utils/test_train_output_handoff.py b/tests/fast/backends/fsdp_utils/test_train_output_handoff.py new file mode 100644 index 000000000..782bc02f2 --- /dev/null +++ b/tests/fast/backends/fsdp_utils/test_train_output_handoff.py @@ -0,0 +1,67 @@ +"""FSDPTrainRayActor.train hands its output to later groups through the object store, not through the driver.""" + +from tests.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=5, suite="stage-a-cpu", labels=[]) + +import ast +from contextlib import nullcontext +from pathlib import Path +from types import SimpleNamespace +from typing import Any + +from miles.utils.ray_utils import Box + + +def _load_train(): + path = Path(__file__).resolve().parents[4] / "miles/backends/fsdp_utils/actor.py" + actor_class = next( + node + for node in ast.parse(path.read_text()).body + if isinstance(node, ast.ClassDef) and node.name == "FSDPTrainRayActor" + ) + train = next(node for node in actor_class.body if isinstance(node, ast.FunctionDef) and node.name == "train") + train.decorator_list = [] + store = {} + + def put(value): + ref = f"ref{len(store)}" + store[ref] = value + return ref + + namespace = dict( + Any=Any, + Box=Box, + ray=SimpleNamespace(get=store.__getitem__, put=put), + dist=SimpleNamespace(get_rank=lambda: 0), + timer=lambda name: nullcontext(), + inverse_timer=lambda name: nullcontext(), + train_metric_utils=SimpleNamespace(log_perf_data_raw=lambda **kwargs: None), + ) + exec(compile(ast.Module(body=[train], type_ignores=[]), str(path), "exec"), namespace) + return namespace["train"], store, put + + +def test_train_unboxes_external_data_and_boxes_its_output(): + train, store, put = _load_train() + seen = {} + + def train_core(rollout_id, rollout_data, external_data): + seen.update(rollout_data=rollout_data, external_data=external_data) + return {"scores": [rollout_id]} + + actor = SimpleNamespace( + args=SimpleNamespace(offload_train=False, debug_rollout_only=False, use_output_store=False), + ema_optimizer=None, + _train_core=train_core, + parallel_state=SimpleNamespace(get_mesh=lambda name: SimpleNamespace(get_local_rank=lambda: 0)), + ) + shard = Box(put({"train_data": []})) + critic_output = Box(put({"scores": [0]})) + + result = train(actor, rollout_id=3, rollout_data_ref=[shard], external_data={"critic": critic_output}) + + assert seen == {"rollout_data": {"train_data": []}, "external_data": {"critic": {"scores": [0]}}} + assert isinstance(result, Box) + assert store[result.inner] == {"scores": [3]} + assert result.inner not in (shard.inner, critic_output.inner) From 2dc35382dfe7d6a469d0e2248edc0afcdf067935 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Tue, 10 Nov 2026 08:52:44 +0000 Subject: [PATCH 03/33] fix(ray): hand later trainer groups the output boxes, not the raw refs train returns Box(ray.put(output)); the driver discarded its ray.get and passed the task refs on, so the consumer's box.inner hit an ObjectRef. Keep the boxes the way the rollout shards are kept. Co-Authored-By: Claude Mythos 5.1 --- train_diffusion.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/train_diffusion.py b/train_diffusion.py index b4075788f..d62b760fd 100644 --- a/train_diffusion.py +++ b/train_diffusion.py @@ -73,8 +73,9 @@ def save(rollout_id): train_outputs = {} for role, train_group in train_groups.items(): logger.info(f"train: rollout {rollout_id} {role} train start") - train_outputs[role] = train_group.async_train(rollout_id, rollout_data_ref, train_outputs) - ray.get(train_outputs[role]) + # Each rank returns a Box around its output's ObjectRef; the driver keeps the boxes (not the payload) + # and hands them to the later groups, as RolloutManager.generate does for the shards. + train_outputs[role] = ray.get(train_group.async_train(rollout_id, rollout_data_ref, train_outputs)) logger.info(f"train: rollout {rollout_id} {role} train done") ray.get(rollout_manager.release.remote(rollout_id)) From a52f72fb45d1f2c720040bbc8a1e88d4f337b3b1 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Sat, 24 Oct 2026 00:03:32 +0000 Subject: [PATCH 04/33] feat(fsdp): add a train-input hook that preprocesses train pairs before micro-batching --- docs/user-guide/cli-reference.md | 1 + docs/user-guide/customization.md | 14 ++ miles/backends/fsdp_utils/actor.py | 35 +++-- miles/utils/arguments.py | 10 ++ .../fsdp_utils/test_train_input_hook.py | 120 ++++++++++++++++++ 5 files changed, 166 insertions(+), 14 deletions(-) create mode 100644 tests/fast/backends/fsdp_utils/test_train_input_hook.py diff --git a/docs/user-guide/cli-reference.md b/docs/user-guide/cli-reference.md index d46290c60..42eaacfa8 100644 --- a/docs/user-guide/cli-reference.md +++ b/docs/user-guide/cli-reference.md @@ -278,6 +278,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 | – | Builds DiT inputs. | | `--custom-loss-function-path` | str | – | Loss **formula** only — the DiT forward stays in the actor. | +| `--custom-train-input-function-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[]`. | | `--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. | diff --git a/docs/user-guide/customization.md b/docs/user-guide/customization.md index 88fa86b64..c467c7cc9 100644 --- a/docs/user-guide/customization.md +++ b/docs/user-guide/customization.md @@ -25,6 +25,7 @@ signatures they expect, and the defaults they replace — in the same spirit as | | `--custom-convert-samples-to-train-data-path` | Full sample → train_data | | | `--custom-prepare-train-batch-path` | DiT batch preparation | | | `--custom-loss-function-path` | Loss formula only | +| | `--custom-train-input-function-path` | Train-pair preprocessing before micro-batching | | | `--custom-train-output-function-path` | Output handed to later trainer groups | | | `--sde-step-backend-path` | Train-side SDE dynamics | | **Logging** | `--custom-rollout-log-function-path` | Train-rollout logging | @@ -283,6 +284,19 @@ 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`. +### `--custom-train-input-function-path` + +```python +def train_input(ctx, train_pairs) -> list: + ... +``` + +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 +and the train-output hook see the returned pairs. + ### `--custom-train-output-function-path` ```python diff --git a/miles/backends/fsdp_utils/actor.py b/miles/backends/fsdp_utils/actor.py index 55858aba7..18f7ebc65 100644 --- a/miles/backends/fsdp_utils/actor.py +++ b/miles/backends/fsdp_utils/actor.py @@ -177,6 +177,11 @@ def init(self, args: Namespace, role: str, with_ref: bool = False) -> int: # ty 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_func = ( + load_function(args.custom_train_input_function_path) + if args.custom_train_input_function_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 @@ -364,6 +369,22 @@ def _train_core(self, rollout_id: int, rollout_data, external_data: dict[str, An if not train_pairs: raise ValueError("rollout_data['train_data'] is empty") + loss_ctx = DiffusionLossContext( + models=self.models, + reference_models=self.reference_models, + teacher_models=self.teacher_models, + train_pipeline_config=self.train_pipeline_config, + sde_backend=self.sde_backend, + args=self.args, + forward_dtype=self._forward_dtype, + device=device, + rollout_id=rollout_id, + dp_rank=self.parallel_state.dp_rank, + external_data=external_data, + ) + if self.custom_train_input_func is not None: + train_pairs = self.custom_train_input_func(loss_ctx, train_pairs) + num_pairs = len(train_pairs) # ------------- Micro-batch schedule ------------- @@ -391,20 +412,6 @@ def _train_core(self, rollout_id: int, rollout_data, external_data: dict[str, An microbatch_schedule=microbatch_schedule, ) - loss_ctx = DiffusionLossContext( - models=self.models, - reference_models=self.reference_models, - teacher_models=self.teacher_models, - train_pipeline_config=self.train_pipeline_config, - sde_backend=self.sde_backend, - args=self.args, - forward_dtype=self._forward_dtype, - device=device, - rollout_id=rollout_id, - dp_rank=self.parallel_state.dp_rank, - external_data=external_data, - ) - # ------------- Recompute old log-probs (impl-consistent PPO ratio) ------------- if self.args.diffusion_recompute_old_log_prob: with timer("recompute_old_log_prob"), torch.no_grad(): diff --git a/miles/utils/arguments.py b/miles/utils/arguments.py index eafaf5fd8..0172a2b8d 100644 --- a/miles/utils/arguments.py +++ b/miles/utils/arguments.py @@ -971,6 +971,16 @@ def add_algo_arguments(parser): "DiT forward is owned by the actor; this hook only computes the objective." ), ) + parser.add_argument( + "--custom-train-input-function-path", + type=str, + default=None, + 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." + ), + ) parser.add_argument( "--custom-train-output-function-path", type=str, diff --git a/tests/fast/backends/fsdp_utils/test_train_input_hook.py b/tests/fast/backends/fsdp_utils/test_train_input_hook.py new file mode 100644 index 000000000..86df537bc --- /dev/null +++ b/tests/fast/backends/fsdp_utils/test_train_input_hook.py @@ -0,0 +1,120 @@ +"""The train-input hook preprocesses a rank's train pairs before they are split into micro-batches. + + train pairs (the converted rollout output) + ctx (external_data from earlier groups) + --train-input hook (filter / reorder / rewrite)--> preprocessed pairs + preprocessed pairs --> micro-batch schedule --> training forwards, in order + preprocessed pairs --> train-output hook (the same ctx) + no hook --> the converted train pairs, as before + +The production _train_core runs on CPU with the forward, metrics and rank checks replaced; the +optimizer step is skipped, so only the pairs and ctx each stage receives are observed. +""" + +from tests.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=5, suite="stage-a-cpu", labels=["fsdp"]) + +import ast +from argparse import Namespace +from contextlib import nullcontext +from pathlib import Path +from types import SimpleNamespace +from typing import Any + +import pytest +import torch + +from miles.backends.fsdp_utils.loss_hub.types import DiffusionLossContext +from miles.utils.train_data_utils import build_microbatch_schedule + + +def _load_train_core(): + path = Path(__file__).resolve().parents[4] / "miles/backends/fsdp_utils/actor.py" + actor_class = next( + node + for node in ast.parse(path.read_text()).body + if isinstance(node, ast.ClassDef) and node.name == "FSDPTrainRayActor" + ) + method = next( + node for node in actor_class.body if isinstance(node, ast.FunctionDef) and node.name == "_train_core" + ) + namespace = dict( + Any=Any, + torch=torch, + DiffusionLossContext=DiffusionLossContext, + build_microbatch_schedule=build_microbatch_schedule, + validate_same_microbatch_counts_across_train_ranks=lambda **kwargs: None, + timer=lambda name: nullcontext(), + new_metric_buffer=lambda *args, **kwargs: SimpleNamespace(reduce=lambda: {}), + ) + exec(compile(ast.Module(body=[method], type_ignores=[]), str(path), "exec"), namespace) + return namespace["_train_core"] + + +def _actor(train_input, train_output, forwarded): + return SimpleNamespace( + models={}, + reference_models={}, + teacher_models={}, + train_pipeline_config=None, + sde_backend=None, + args=Namespace( + num_steps_per_rollout=2, + micro_batch_size=1, + loss_type="policy_loss", + diffusion_recompute_old_log_prob=False, + debug_skip_optimizer_step=True, + log_loss_sigma_bucket=0, + ), + _forward_dtype=torch.float32, + parallel_state=SimpleNamespace(dp_rank=0, dp_group=None), + custom_train_input_func=train_input, + custom_train_output_func=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, + _forward_train_pair_batch=lambda ctx, chunk, **kwargs: forwarded.append((ctx.microbatch_id, chunk)), + _log_metrics=lambda rollout_id, metrics, step: None, + ) + + +@pytest.fixture(autouse=True) +def _cpu_device(monkeypatch): + monkeypatch.setattr(torch.cuda, "current_device", lambda: 0) + + +def test_later_stages_see_the_preprocessed_pairs(): + pairs = [{"sample_index": index} for index in range(6)] + scores = {1: 0.1, 2: 0.2, 4: 0.4, 5: 0.5} + seen_by_input = [] + + def train_input(ctx, train_pairs): + seen_by_input.append((ctx, list(train_pairs))) + critic = ctx.external_data["critic"] + return [ + {**pair, "score": critic[pair["sample_index"]]} for pair in train_pairs if pair["sample_index"] in critic + ] + + forwarded = [] + actor = _actor(train_input, lambda ctx, train_pairs: (ctx, train_pairs), forwarded) + ctx, output_pairs = _load_train_core()( + actor, rollout_id=3, rollout_data={"train_data": pairs}, external_data={"critic": scores} + ) + + preprocessed = [{"sample_index": index, "score": scores[index]} for index in (1, 2, 4, 5)] + assert seen_by_input == [(ctx, pairs)] + assert (ctx.rollout_id, ctx.external_data) == (3, {"critic": scores}) + assert forwarded == [(microbatch_id, [pair]) for microbatch_id, pair in enumerate(preprocessed)] + assert output_pairs == preprocessed + assert actor.global_step == 2 + + +def test_without_the_hook_the_converted_pairs_train(): + pairs = [{"sample_index": index} for index in range(4)] + forwarded = [] + actor = _actor(None, lambda ctx, train_pairs: train_pairs, forwarded) + + output_pairs = _load_train_core()(actor, rollout_id=0, rollout_data={"train_data": pairs}, external_data={}) + + assert forwarded == [(index, [pair]) for index, pair in enumerate(pairs)] + assert output_pairs == pairs From 77dedd4e15e1c2b31c40172f006a837b00764b8a Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Mon, 9 Nov 2026 22:41:02 +0000 Subject: [PATCH 05/33] refactor(fsdp): rename the train-input hook to custom_train_input_postprocess Review on #338: `custom_train_input_postprocess_func` says what the hook does, a post-processing step on the converted train pairs. The flag follows the prepare hook's pattern: `--custom-train-input-postprocess-path` sets `args.custom_train_input_postprocess_path`, loaded into `self.custom_train_input_postprocess_func`. Docs and the hook test follow. Co-Authored-By: Claude Mythos 5.1 --- docs/user-guide/cli-reference.md | 2 +- docs/user-guide/customization.md | 4 ++-- miles/backends/fsdp_utils/actor.py | 10 +++++----- miles/utils/arguments.py | 2 +- .../fast/backends/fsdp_utils/test_train_input_hook.py | 2 +- 5 files changed, 10 insertions(+), 10 deletions(-) diff --git a/docs/user-guide/cli-reference.md b/docs/user-guide/cli-reference.md index 42eaacfa8..c5b1411cc 100644 --- a/docs/user-guide/cli-reference.md +++ b/docs/user-guide/cli-reference.md @@ -278,7 +278,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 | – | Builds DiT inputs. | | `--custom-loss-function-path` | str | – | Loss **formula** only — the DiT forward stays in the actor. | -| `--custom-train-input-function-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-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[]`. | | `--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. | diff --git a/docs/user-guide/customization.md b/docs/user-guide/customization.md index c467c7cc9..872576f71 100644 --- a/docs/user-guide/customization.md +++ b/docs/user-guide/customization.md @@ -25,7 +25,7 @@ signatures they expect, and the defaults they replace — in the same spirit as | | `--custom-convert-samples-to-train-data-path` | Full sample → train_data | | | `--custom-prepare-train-batch-path` | DiT batch preparation | | | `--custom-loss-function-path` | Loss formula only | -| | `--custom-train-input-function-path` | Train-pair preprocessing before micro-batching | +| | `--custom-train-input-postprocess-path` | Train-pair preprocessing before micro-batching | | | `--custom-train-output-function-path` | Output handed to later trainer groups | | | `--sde-step-backend-path` | Train-side SDE dynamics | | **Logging** | `--custom-rollout-log-function-path` | Train-rollout logging | @@ -284,7 +284,7 @@ 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`. -### `--custom-train-input-function-path` +### `--custom-train-input-postprocess-path` ```python def train_input(ctx, train_pairs) -> list: diff --git a/miles/backends/fsdp_utils/actor.py b/miles/backends/fsdp_utils/actor.py index 18f7ebc65..dcfbb7dd4 100644 --- a/miles/backends/fsdp_utils/actor.py +++ b/miles/backends/fsdp_utils/actor.py @@ -177,9 +177,9 @@ def init(self, args: Namespace, role: str, with_ref: bool = False) -> int: # ty 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_func = ( - load_function(args.custom_train_input_function_path) - if args.custom_train_input_function_path is not 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 = ( @@ -382,8 +382,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_func is not None: - train_pairs = self.custom_train_input_func(loss_ctx, train_pairs) + if self.custom_train_input_postprocess_func is not None: + train_pairs = self.custom_train_input_postprocess_func(loss_ctx, train_pairs) num_pairs = len(train_pairs) diff --git a/miles/utils/arguments.py b/miles/utils/arguments.py index 0172a2b8d..1bd0d6e19 100644 --- a/miles/utils/arguments.py +++ b/miles/utils/arguments.py @@ -972,7 +972,7 @@ def add_algo_arguments(parser): ), ) parser.add_argument( - "--custom-train-input-function-path", + "--custom-train-input-postprocess-path", type=str, default=None, help=( 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 86df537bc..b6525ac0d 100644 --- a/tests/fast/backends/fsdp_utils/test_train_input_hook.py +++ b/tests/fast/backends/fsdp_utils/test_train_input_hook.py @@ -68,7 +68,7 @@ def _actor(train_input, train_output, forwarded): ), _forward_dtype=torch.float32, parallel_state=SimpleNamespace(dp_rank=0, dp_group=None), - custom_train_input_func=train_input, + custom_train_input_postprocess_func=train_input, custom_train_output_func=train_output, optimizer=SimpleNamespace(zero_grad=lambda set_to_none: None), global_step=0, From 4868030abd06b86e3cee625a7ceed9b3586a03d9 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Mon, 19 Oct 2026 20:12:21 +0000 Subject: [PATCH 06/33] feat(rollout): stop the rollout at a random step for DMD2 backward simulation --- docs/user-guide/cli-reference.md | 2 +- docs/user-guide/customization.md | 6 ++-- miles/rollout/sglang_diffusion_rollout.py | 3 +- miles/rollout/step_strategy_hub.py | 32 +++++++++++++------- miles/utils/arguments.py | 2 +- tests/fast/rollout/test_step_strategy_hub.py | 25 ++++++++++++--- 6 files changed, 50 insertions(+), 20 deletions(-) diff --git a/docs/user-guide/cli-reference.md b/docs/user-guide/cli-reference.md index c5b1411cc..d05802471 100644 --- a/docs/user-guide/cli-reference.md +++ b/docs/user-guide/cli-reference.md @@ -200,7 +200,7 @@ See [Dtype Control](../advanced/dtype-control.md). | `--diffusion-num-sde-steps` | int | `0` | Read by the step strategy. | | `--diffusion-sde-window-range` | `"lo,hi"` | – | For `sde_window`. Defaults to `[0, num_inference_steps)`. | | `--diffusion-sde-candidate-steps` | `"1,2,3"` | – | Required by `epoch_global_random_choice`. | -| `--diffusion-step-strategy-path` | str | – | `(args, sample, num_steps, seed) -> (sde, ret)` choosing the SDE and returned steps, e.g. `miles.rollout.step_strategy_hub.sde_window`. Flow-GRPO needs one. | +| `--diffusion-step-strategy-path` | str | – | `(args, sample, num_steps, seed) -> (sde, ret, stop)` choosing the SDE, returned and last steps, e.g. `miles.rollout.step_strategy_hub.sde_window`. Flow-GRPO needs one. | | `--rollout-return-full-trajectory` | flag | off | Ask the engine for the whole denoising trajectory instead of only the steps the step strategy requests. The train tensors are identical; kept for debugging and A/B runs. | | `--diffusion-log-prob-no-const` | flag | off | Drop log-prob constants on the engine (pairs with the CPS backend). Forced on for `cps` / `ode`. | | `--diffusion-generator-device` | str | `cuda` | | diff --git a/docs/user-guide/customization.md b/docs/user-guide/customization.md index 872576f71..47516d3aa 100644 --- a/docs/user-guide/customization.md +++ b/docs/user-guide/customization.md @@ -99,10 +99,11 @@ latents the engine ships back for the trainer. Stock implementations live in `miles/rollout/step_strategy_hub.py`. ```python -def strategy(args, sample, num_steps, seed) -> tuple[list[int] | None, list[int] | None]: - # returns (sde_step_indices, return_step_indices) +def strategy(args, sample, num_steps, seed) -> tuple[list[int] | None, list[int] | None, int | None]: + # returns (sde_step_indices, return_step_indices, stop_step_index) # sde None = no per-step filter: every step uses --diffusion-sde-type # return None = the engine returns every step's latent + # stop None = the engine runs every step; otherwise its last step goes straight to sigma 0 ... ``` @@ -114,6 +115,7 @@ steps for debugging / A-B runs. | `sde_window` | Random contiguous window (`--diffusion-num-sde-steps`, `--diffusion-sde-window-range`); returns all latents its steps touch | | `epoch_global_random_choice` | Subset of `--diffusion-sde-candidate-steps`, shared by each block of `--rollout-batch-size` consecutive prompt groups (one rollout, unless a dynamic-sampling filter drops groups); returns all latents its steps touch | | `ode_and_return_last` | No step filter (every step uses `--diffusion-sde-type`, which the DiffusionNFT recipes set to `ode`); return only the final clean `x0` | +| `stop_at_random_step` | DMD2 backward simulation: no step filter; stop at a random step `i` and return `x_i` plus its `x0` prediction | DiffusionNFT picks the timesteps it trains on with a separate hook, `--diffusion-nft-timestep-strategy-path`: `(args, num_steps, generator) -> list[int]`, built in diff --git a/miles/rollout/sglang_diffusion_rollout.py b/miles/rollout/sglang_diffusion_rollout.py index 2135365c6..6b23cf662 100644 --- a/miles/rollout/sglang_diffusion_rollout.py +++ b/miles/rollout/sglang_diffusion_rollout.py @@ -179,7 +179,7 @@ async def generate_microgroup( # SGL-D TODO: support seed list for multiple samples in one request # currently only support assigning the first seed, SGL-D generates samples with seed, seed+1, seed+2, ... if not evaluation and state.step_strategy_fn is not None: - sde_indices, return_indices = state.step_strategy_fn( + sde_indices, return_indices, stop_index = state.step_strategy_fn( args, microgroup[0], int(sampling_params["num_inference_steps"]), @@ -189,6 +189,7 @@ async def generate_microgroup( return_indices = None # None asks the engine for every step sampling_params["rollout_sde_step_indices"] = sde_indices sampling_params["rollout_return_step_indices"] = return_indices + sampling_params["rollout_stop_step_index"] = stop_index else: sde_indices = None diff --git a/miles/rollout/step_strategy_hub.py b/miles/rollout/step_strategy_hub.py index 3ecc893a0..a59e3b3fe 100644 --- a/miles/rollout/step_strategy_hub.py +++ b/miles/rollout/step_strategy_hub.py @@ -1,11 +1,13 @@ """Library of functions that fill ``rollout_sde_step_indices`` / -``rollout_return_step_indices`` for one sglang-diffusion rollout request. +``rollout_return_step_indices`` / ``rollout_stop_step_index`` for one +sglang-diffusion rollout request. -Each function has signature ``(args, sample, num_steps, seed) -> (sde, ret)``, -both ``list[int] | None``. A strategy owns both halves of the request: +Each function has signature ``(args, sample, num_steps, seed) -> (sde, ret, stop)``, +``sde`` and ``ret`` are ``list[int] | None``, ``stop`` is ``int | None``. A strategy owns the whole request: ``sde`` picks the steps sampled as SDE (``None`` = no SDE steps, a pure ODE -rollout), and ``ret`` picks the trajectory latents the engine ships back for -the trainer (``None`` = all steps). +rollout), ``ret`` picks the trajectory latents the engine ships back for +the trainer (``None`` = all steps), and ``stop`` is the last step the engine +runs, sent straight to sigma 0 (``None`` = all steps). Point ``--diffusion-step-strategy-path`` at any such function. """ @@ -27,7 +29,7 @@ def _sde_steps_to_latent_indices(indices: list[int]) -> list[int]: def sde_window( args: Namespace, sample: Sample, num_steps: int, seed: int -) -> tuple[list[int] | None, list[int] | None]: +) -> tuple[list[int] | None, list[int] | None, int | None]: """flow_grpo-style random contiguous SDE window; the engine returns all latents the window's steps touch (x_i and x_{i+1} for each step i).""" window_size = int(args.diffusion_num_sde_steps) @@ -48,12 +50,12 @@ def sde_window( rng = np.random.default_rng(seed) start = int(rng.integers(lo, hi - window_size + 1)) indices = list(range(start, start + window_size)) - return indices, _sde_steps_to_latent_indices(indices) + return indices, _sde_steps_to_latent_indices(indices), None def epoch_global_random_choice( args: Namespace, sample: Sample, num_steps: int, seed: int -) -> tuple[list[int] | None, list[int] | None]: +) -> tuple[list[int] | None, list[int] | None, int | None]: """Per-epoch global random SDE subset: draw ``--diffusion-num-sde-steps`` candidate steps at random once per epoch (every sample in the epoch shares them), returned in ascending step order (matches the wan2.2 recipe).""" @@ -68,15 +70,23 @@ def epoch_global_random_choice( generator = torch.Generator().manual_seed(epoch + int(args.rollout_seed)) selected = torch.randperm(len(candidates), generator=generator)[:num_sde_steps] indices = sorted(candidates[i] for i in selected.tolist()) - return indices, _sde_steps_to_latent_indices(indices) + return indices, _sde_steps_to_latent_indices(indices), None def ode_and_return_last( args: Namespace, sample: Sample, num_steps: int, seed: int -) -> tuple[list[int] | None, list[int] | None]: +) -> tuple[list[int] | None, list[int] | None, int | None]: """DiffusionNFT-style request: no SDE steps (pure ODE rollout) and only the final clean x0 shipped back.""" - return None, [num_steps] + return None, [num_steps], None + + +def stop_at_random_step( + args: Namespace, sample: Sample, num_steps: int, seed: int +) -> tuple[list[int] | None, list[int] | None, int | None]: + """DMD2 backward simulation: stop at a random step i and ship x_i plus its x0 prediction.""" + stop = int(np.random.default_rng(seed).integers(num_steps)) + return None, [stop, stop + 1], stop def _sde_candidate_steps(args: Namespace, num_steps: int) -> list[int]: diff --git a/miles/utils/arguments.py b/miles/utils/arguments.py index 1bd0d6e19..2b2866030 100644 --- a/miles/utils/arguments.py +++ b/miles/utils/arguments.py @@ -439,7 +439,7 @@ def add_rollout_arguments(parser): type=str, default=None, help="Dotted path to `fn(args, sample, num_steps, seed) -> (sde_step_indices, " - "returned_latent_indices)`, called per engine request. The built-ins in " + "returned_latent_indices, stop_step_index)`, called per engine request. The built-ins in " "miles.rollout.step_strategy_hub read --diffusion-num-sde-steps.", ) parser.add_argument( diff --git a/tests/fast/rollout/test_step_strategy_hub.py b/tests/fast/rollout/test_step_strategy_hub.py index 312f5985e..29a256b70 100644 --- a/tests/fast/rollout/test_step_strategy_hub.py +++ b/tests/fast/rollout/test_step_strategy_hub.py @@ -7,16 +7,22 @@ from argparse import Namespace -from miles.rollout.step_strategy_hub import epoch_global_random_choice, ode_and_return_last, sde_window +from miles.rollout.step_strategy_hub import ( + epoch_global_random_choice, + ode_and_return_last, + sde_window, + stop_at_random_step, +) from miles.utils.types import Sample def test_sde_window_returns_window_plus_boundary(): args = Namespace(diffusion_num_sde_steps=3, diffusion_sde_window_range="0,10") - sde, ret = sde_window(args, Sample(), num_steps=10, seed=7) + sde, ret, stop = sde_window(args, Sample(), num_steps=10, seed=7) assert sde == list(range(sde[0], sde[0] + 3)) assert ret == sorted(set(sde) | {i + 1 for i in sde}) + assert stop is None def test_epoch_global_random_choice_returns_subset_plus_boundary(): @@ -26,11 +32,22 @@ def test_epoch_global_random_choice_returns_subset_plus_boundary(): rollout_batch_size=4, rollout_seed=0, ) - sde, ret = epoch_global_random_choice(args, Sample(group_index=0), num_steps=10, seed=7) + sde, ret, stop = epoch_global_random_choice(args, Sample(group_index=0), num_steps=10, seed=7) assert len(sde) == 2 and set(sde) <= {1, 3, 5, 7} assert ret == sorted(set(sde) | {i + 1 for i in sde}) + assert stop is None def test_ode_and_return_last_requests_only_x0(): - assert ode_and_return_last(Namespace(), Sample(), num_steps=10, seed=7) == (None, [10]) + assert ode_and_return_last(Namespace(), Sample(), num_steps=10, seed=7) == (None, [10], None) + + +def test_stop_at_random_step_ships_x_i_and_its_x0_prediction(): + stops = set() + for seed in range(32): + sde, ret, stop = stop_at_random_step(Namespace(), Sample(), num_steps=4, seed=seed) + assert sde is None + assert ret == [stop, stop + 1] + stops.add(stop) + assert stops == set(range(4)) From 6f9884bba4d7185e48a5a47ebc3dfa45b5849340 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Mon, 19 Oct 2026 23:10:06 +0000 Subject: [PATCH 07/33] feat(dmd2): train a fake-score critic group from the teacher and score the student's samples --- docs/fsdp_model_roles.md | 8 +- docs/user-guide/cli-reference.md | 10 +- docs/user-guide/customization.md | 13 +- miles/backends/fsdp_utils/actor.py | 9 +- miles/backends/fsdp_utils/loss_hub/dmd2.py | 155 +++++++++ miles/backends/fsdp_utils/loss_hub/sft.py | 8 +- miles/backends/fsdp_utils/loss_hub/types.py | 3 + miles/ray/data_conversion_hub/dmd2.py | 43 +++ miles/utils/arguments.py | 102 +++++- miles/utils/trainer_config.py | 20 +- .../backends/fsdp_utils/test_loss_hub_dmd2.py | 310 ++++++++++++++++++ tests/fast/rollout/test_dmd2_convert.py | 68 ++++ tests/fast/utils/test_dmd2_arguments.py | 117 +++++++ tests/fast/utils/test_trainer_config.py | 36 ++ 14 files changed, 887 insertions(+), 15 deletions(-) create mode 100644 miles/backends/fsdp_utils/loss_hub/dmd2.py create mode 100644 miles/ray/data_conversion_hub/dmd2.py create mode 100644 tests/fast/backends/fsdp_utils/test_loss_hub_dmd2.py create mode 100644 tests/fast/rollout/test_dmd2_convert.py create mode 100644 tests/fast/utils/test_dmd2_arguments.py diff --git a/docs/fsdp_model_roles.md b/docs/fsdp_model_roles.md index 74db273c4..372ee4c10 100644 --- a/docs/fsdp_model_roles.md +++ b/docs/fsdp_model_roles.md @@ -36,10 +36,10 @@ The existing loss receives the reference prediction, and custom prepare/loss hoo access `ctx.reference_models` by component name. A third source, the teacher (`--teacher-load`, with `--teacher-lora-adapter-path` for its -adapters), is reserved for a DMD2-style loss that miles does not ship yet. Until then 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()`. +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()`. 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 d05802471..386de7b9d 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`. | +| `--loss-type` | `policy_loss` | `policy_loss` (Flow-GRPO), `nft`, `sft_loss`, `custom_loss`, `dmd2`. | | `--advantage-estimator` | `grpo` | Only `grpo` today. | | `--diffusion-clip-range` | `1e-4` | PPO ratio clip. | | `--diffusion-adv-clip-max` | `5.0` | Advantage clamp. | @@ -260,7 +260,7 @@ See [Dtype Control](../advanced/dtype-control.md). | Flag | Type | Default | Notes | |---|---|---|---| -| `--loss-type` | enum | `policy_loss` | `policy_loss` / `nft` / `sft_loss` / `custom_loss`. | +| `--loss-type` | enum | `policy_loss` | `policy_loss` / `nft` / `sft_loss` / `custom_loss` / `dmd2`. | | `--advantage-estimator` | enum | `grpo` | | | `--disable-grpo-std-normalization` | flag | off | Subtract the group mean only; skip dividing by the group std. Std normalization is also skipped when `n_samples_per_prompt == 1`, since a one-sample group has no std. With `--globalize-reward-mean` the batch mean is subtracted instead, and the batch-wide std from `--globalize-reward-std` is skipped too. | | `--globalize-reward-mean` | flag | off | Leave **off** for flow_grpo parity. | @@ -284,6 +284,12 @@ See [Dtype Control](../advanced/dtype-control.md). | `--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`. | | `--no-diffusion-nft-adaptive-weight` | flag | off | | +| `--dmd2-critic-steps-per-rollout` | int | `5` | Critic optimizer steps per rollout under `dmd2`, before the actor's single step. Each DP shard must split into this many steps. The last step's samples are scored by the critic before that step's update. | +| `--dmd2-teacher-guidance-scale` | float | – | Required by `dmd2`: the teacher's CFG scale when scoring the student's samples; `1` runs it unguided. | +| `--dmd2-score-sigma-range` | float float | `0.02 0.98` | `MIN MAX` of the unshifted sigma at which `dmd2` scores the student's samples: the last critic step draws grid points in this range and reads them through the visual `--fsdp-flow-shift`. The default is the reference DMD2 range. | +| `--dmd2-critic-loss-space` | str | `velocity` | `velocity` or `x0`: the space of the critic's flow-matching loss. `x0` regresses x0 = x_σ − σ·v, which weights the velocity MSE by σ². | +| `--critic-load` | str | `--teacher-load` | `dmd2` only: HF pipeline checkpoint the critic starts from. Its checkpoints go to the sibling `<--save>_critic` dir. | +| `--critic-lr` | float | `--lr` | `dmd2` only: the critic's learning rate. | ### Reward diff --git a/docs/user-guide/customization.md b/docs/user-guide/customization.md index 47516d3aa..313c015b6 100644 --- a/docs/user-guide/customization.md +++ b/docs/user-guide/customization.md @@ -33,7 +33,7 @@ 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`) is the +`--loss-type` (`policy_loss` / `nft` / `sft_loss` / `custom_loss` / `dmd2`) is the shortcut that auto-fills several of the train-side paths; see § Training. *** @@ -234,11 +234,16 @@ def buffer_filter( | `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` | your prepare | your 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. +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"]`. DiT forward always stays in the FSDP actor; the loss hook only computes the objective. @@ -308,7 +313,9 @@ def train_output(ctx, train_pairs) -> Any: 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[]`. +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 +starts empty on each train call. ### `--sde-step-backend-path` diff --git a/miles/backends/fsdp_utils/actor.py b/miles/backends/fsdp_utils/actor.py index dcfbb7dd4..6fb4916b5 100644 --- a/miles/backends/fsdp_utils/actor.py +++ b/miles/backends/fsdp_utils/actor.py @@ -316,11 +316,15 @@ def update_weights(self, previous_ema: bool = False) -> None: # type: ignore[ov self.weight_updater.update_weights() clear_memory() + def _metric_role_tag(self) -> str: + # Upstream miles tags the train metrics of non-actor trainers, e.g. train/critic-loss. + return "" if self.role == "actor" else f"{self.role}-" + def _log_metrics(self, rollout_id: int, log_dict: dict[str, float], step: int) -> None: """Emit already-reduced metrics; every DP group computed the same values.""" if dist.get_rank() != 0: return - log_dict["train/lr"] = float(self.optimizer.param_groups[0]["lr"]) + log_dict[f"train/{self._metric_role_tag()}lr"] = float(self.optimizer.param_groups[0]["lr"]) log_dict["train/epoch"] = float(rollout_id) log_dict["rollout/step"] = compute_rollout_step(self.args, rollout_id) log_dict["train/step"] = float(step) @@ -443,6 +447,7 @@ def _train_core(self, rollout_id: int, rollout_data, external_data: dict[str, An microbatch_id = 0 for optim_step_idx, microbatch_ranges in enumerate(microbatch_schedule): self.optimizer.zero_grad(set_to_none=True) + loss_ctx.optim_step_idx = optim_step_idx old_log_prob_from_new = self.args.diffusion_recompute_old_log_prob and optim_step_idx == 0 @@ -489,7 +494,7 @@ def _train_core(self, rollout_id: int, rollout_data, external_data: dict[str, An self.optimizer.zero_grad(set_to_none=True) self.global_step += 1 - reduced = {f"train/{key}": value for key, value in metrics.reduce().items()} + 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: diff --git a/miles/backends/fsdp_utils/loss_hub/dmd2.py b/miles/backends/fsdp_utils/loss_hub/dmd2.py new file mode 100644 index 000000000..001690a78 --- /dev/null +++ b/miles/backends/fsdp_utils/loss_hub/dmd2.py @@ -0,0 +1,155 @@ +"""DMD2 critic-group hooks: the critic (fake score) learns the student's samples and scores those of its last step.""" + +from __future__ import annotations + +import dataclasses + +import torch + +from miles.backends.fsdp_utils.ema import reshard_model +from miles.backends.fsdp_utils.input_dtype_policy import apply_input_dtype_policy +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.metric_buffer import MetricBuffer + + +def prepare_critic_batch( + ctx: DiffusionLossContext, + batch: list[dict], + *, + pad_to_len: int | None = None, +) -> PreparedBatch: + """SFT flow matching on the student's x0 predictions, conditioned on their rollout prompts. + + The last step's samples are scored at their noisy inputs, so its grid points come from the scoring range. + """ + config = ctx.train_pipeline_config + sft_batch = [ + { + "latent": {"visual": pair["x0"]}, + "cond_kwargs": config.prepare_cond_kwargs(pair["denoising_env"].pos_cond_kwargs, ctx.device), + } + for pair in batch + ] + grid_index_range = None + if _is_scoring_step(ctx): + min_sigma, max_sigma = ctx.args.dmd2_score_sigma_range + num_train_timesteps = config.num_train_timesteps + # Grid index i carries the unshifted sigma 1 - i / num_train_timesteps. + grid_index_range = (round(num_train_timesteps * (1 - max_sigma)), round(num_train_timesteps * (1 - min_sigma))) + return prepare_sft_batch(ctx, sft_batch, pad_to_len=pad_to_len, grid_index_range=grid_index_range) + + +def critic_loss_formula( + ctx: DiffusionLossContext, + batch: list[dict], + prepared: PreparedBatch, + *, + new_pred: dict[str, torch.Tensor], + old_pred: dict[str, torch.Tensor] | None, + ref_pred: dict[str, torch.Tensor] | None, + metrics: MetricBuffer, + write_old_log_prob: bool = False, + old_log_prob_from_new: bool = False, +) -> torch.Tensor: + """The SFT loss in --dmd2-critic-loss-space. + + On the last step it also keeps the critic's x0 at each noisy input, before that step's update. + """ + latents = prepared.latents["visual"] + sigmas = prepared.extras["sigmas"]["visual"].view(len(batch), *([1] * (latents.ndim - 1))) + if _is_scoring_step(ctx): + x0_fake = latents - sigmas * new_pred["visual"].detach().float() + ctx.train_output_inputs.append( + (batch, prepared.component_name, latents, prepared.timesteps["visual"], sigmas, x0_fake) + ) + if ctx.args.dmd2_critic_loss_space == "x0": + # x0 = x_sigma - sigma v, so the MSE on x0 weights the velocity MSE by sigma^2. + x0_target = latents - sigmas * prepared.extras["target"]["visual"] + prepared = dataclasses.replace(prepared, extras={**prepared.extras, "target": {"visual": x0_target}}) + new_pred = {"visual": latents - sigmas * new_pred["visual"].float()} + return sft_loss_formula( + 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, + ) + + +def score_last_step_samples(ctx: DiffusionLossContext, train_pairs: list[dict]) -> dict[int, dict]: + """The teacher's x0 at each scored sample's noisy input, next to the critic's x0 kept there, by sample.""" + predictions = {} + for batch, component_name, latents, timesteps, sigmas, x0_fake in ctx.train_output_inputs: + teacher = ctx.teacher_models[component_name] + real_pred = _predict_velocity(ctx, teacher, batch, latents, timesteps, ctx.args.dmd2_teacher_guidance_scale) + for pair, x0_real, fake in zip(batch, latents - sigmas * real_pred, x0_fake, strict=True): + predictions[pair["sample_index"]] = {"x0_real": x0_real.cpu(), "x0_fake": fake.cpu()} + + # A no-grad forward leaves FSDP's root parameters gathered; sleep must move the shards. + for model in ctx.teacher_models.values(): + reshard_model(model) + return predictions + + +def _is_scoring_step(ctx: DiffusionLossContext) -> bool: + return ctx.optim_step_idx == ctx.args.num_steps_per_rollout - 1 + + +def _predict_velocity( + ctx: DiffusionLossContext, + model: torch.nn.Module, + batch: list[dict], + latents: torch.Tensor, + timesteps: torch.Tensor, + guidance_scale: float, +) -> torch.Tensor: + """One velocity prediction, with CFG over the rollout's negative cond when ``guidance_scale > 1``.""" + config = ctx.train_pipeline_config + use_cfg = guidance_scale > 1.0 + envs = [pair["denoising_env"] for pair in batch] + if use_cfg and any(env.neg_cond_kwargs is None for env in envs): + raise ValueError( + "--dmd2-teacher-guidance-scale > 1 needs the rollout's negative cond, " + "which the engine returns only for requests that run CFG" + ) + pos_list = [config.prepare_cond_kwargs(env.pos_cond_kwargs, ctx.device) for env in envs] + neg_list = [config.prepare_cond_kwargs(env.neg_cond_kwargs, ctx.device) for env in envs] if use_cfg else [] + cfg_batching = use_cfg and config.cfg_batching + pos_cond = neg_cond = joint_cond = None + if cfg_batching: + joint_cond = config.collate_cond_for_sample_batch(pos_list + neg_list, ctx.device) + else: + pos_cond = config.collate_cond_for_sample_batch(pos_list, ctx.device) + if use_cfg: + neg_cond = config.collate_cond_for_sample_batch(neg_list, ctx.device) + + latents_in, timesteps_in, (pos_in, neg_in, joint_in) = apply_input_dtype_policy( + config.input_dtype_policy, + latents={"visual": latents}, + timesteps={"visual": config.process_timestep_as_input(timesteps)}, + conds=(pos_cond, neg_cond, joint_cond), + default_dtype=ctx.forward_dtype, + ) + with torch.autocast( + "cuda", + dtype=ctx.forward_dtype, + enabled=ctx.forward_dtype != torch.float32 and config.enable_autocast, + ): + pred = config.compute_noise_pred( + model=model, + latents_input=latents_in, + timesteps_input=timesteps_in, + pos_cond=pos_in, + neg_cond=neg_in, + joint_cond=joint_in, + use_cfg=use_cfg, + cfg_batching=cfg_batching, + guidance_scale=guidance_scale, + true_cfg_scale=None, + ) + return pred["visual"].float() diff --git a/miles/backends/fsdp_utils/loss_hub/sft.py b/miles/backends/fsdp_utils/loss_hub/sft.py index 5c120c228..b17acfae7 100644 --- a/miles/backends/fsdp_utils/loss_hub/sft.py +++ b/miles/backends/fsdp_utils/loss_hub/sft.py @@ -39,11 +39,13 @@ def prepare_sft_batch( batch: list[dict], *, pad_to_len: int | None = None, + grid_index_range: tuple[int, int] | None = None, ) -> PreparedBatch: """Corrupt every latent stream at one shared grid index, each through its own shifted grid; CFG-free cached cond. - The visual grid picks the DiT component and the index is drawn uniformly from the points it serves. Sharing the - index pairs the streams' sigmas as inference steps them, one step index read through each stream's shift. + The visual grid picks the DiT component and the index is drawn uniformly from the points it serves, within + ``grid_index_range`` (inclusive) when given. Sharing the index pairs the streams' sigmas as inference steps them, + one step index read through each stream's shift. """ device = ctx.device config = ctx.train_pipeline_config @@ -57,6 +59,8 @@ def prepare_sft_batch( for stream_name in stream_names } component_name, model, visual_pool = select_component(ctx, noise_schedules["visual"], device) + if grid_index_range is not None: + visual_pool = visual_pool[(visual_pool >= grid_index_range[0]) & (visual_pool <= grid_index_range[1])] # The visual stream keeps the single-stream seed, so single-stream runs draw as before; other streams add their # name, so adding a stream never changes another stream's noise. diff --git a/miles/backends/fsdp_utils/loss_hub/types.py b/miles/backends/fsdp_utils/loss_hub/types.py index 2d41b3537..fec342ea8 100644 --- a/miles/backends/fsdp_utils/loss_hub/types.py +++ b/miles/backends/fsdp_utils/loss_hub/types.py @@ -22,10 +22,13 @@ class DiffusionLossContext: device: torch.device rollout_id: int = 0 microbatch_id: int = 0 + optim_step_idx: int = 0 dp_rank: int = 0 reference_models: dict[str, torch.nn.Module] = field(default_factory=dict) teacher_models: dict[str, torch.nn.Module] = field(default_factory=dict) external_data: dict[str, Any] = field(default_factory=dict) + # Filled by loss hooks during one train call and read by the train-output hook. + train_output_inputs: list[Any] = field(default_factory=list) @dataclass(frozen=True) diff --git a/miles/ray/data_conversion_hub/dmd2.py b/miles/ray/data_conversion_hub/dmd2.py new file mode 100644 index 000000000..cc0b1cee3 --- /dev/null +++ b/miles/ray/data_conversion_hub/dmd2.py @@ -0,0 +1,43 @@ +"""Convert DMD2 rollout samples, each stopped at its step i, into one train pair per sample.""" + +from argparse import Namespace +from typing import Any + +from miles.utils.types import Sample + + +def expand_samples_to_train_pairs( + args: Namespace, + samples: list[Sample], + rewards: list[float], + raw_rewards: list[float], +) -> dict[str, Any]: + """One pair per sample: the student's input ``x_i`` at its stop step ``i`` and its x0 prediction there.""" + train_data: list[dict[str, Any]] = [] + for sample in samples: + traj = sample.dit_trajectory + if traj is None or traj.latent_step_indices is None or sample.denoising_env is None: + raise ValueError( + f"sample {sample.index} missing dit_trajectory.latent_step_indices or denoising_env; " + "DMD2 rollouts need --diffusion-step-strategy-path miles.rollout.step_strategy_hub.stop_at_random_step" + ) + step_index = int(traj.latent_step_indices[0]) + # The engine sends step i straight to sigma 0, so the grid ends right after sigma_i. + if traj.latent_step_indices.tolist() != [step_index, step_index + 1] or len(traj.sigmas) != step_index + 2: + raise ValueError( + f"sample {sample.index} returned steps {traj.latent_step_indices.tolist()} on a " + f"{len(traj.sigmas)}-point sigma grid; DMD2 needs a rollout stopped at its first returned step" + ) + train_data.append( + { + "latent": traj.latents[0], + "x0": traj.latents[1], + "timestep": float(traj.timesteps[step_index]), + "sigma": float(traj.sigmas[step_index]), + "step_index": step_index, + "denoising_env": sample.denoising_env, + "sample_index": sample.index, + "prompt": sample.prompt, + } + ) + return {"train_data": train_data} diff --git a/miles/utils/arguments.py b/miles/utils/arguments.py index 2b2866030..639b4f029 100644 --- a/miles/utils/arguments.py +++ b/miles/utils/arguments.py @@ -943,11 +943,12 @@ def add_algo_arguments(parser): parser.add_argument( "--loss-type", type=str, - choices=["policy_loss", "sft_loss", "custom_loss", "nft"], + 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 selects the DMD2 train-data converter and trains a critic group next to the actor. " "DiT forward always stays in the FSDP actor." ), ) @@ -1019,6 +1020,47 @@ def add_algo_arguments(parser): help="Sampling steps the built-in NFT timestep strategies drop: random ones per sample for " "drop_random_steps, the final (lowest-noise) ones for drop_final_steps.", ) + parser.add_argument( + "--dmd2-critic-steps-per-rollout", + type=int, + default=5, + help="DMD2 critic optimizer steps per rollout, taken before the actor's single step (TTUR).", + ) + parser.add_argument( + "--dmd2-teacher-guidance-scale", + type=float, + default=None, + help="CFG scale of the frozen teacher when DMD2 scores the student's samples; 1 runs it unguided.", + ) + parser.add_argument( + "--dmd2-score-sigma-range", + type=float, + nargs=2, + metavar=("MIN", "MAX"), + default=[0.02, 0.98], + help="Unshifted sigma range in which DMD2 scores the student's samples: the grid points between MIN " + "and MAX, read through the visual --fsdp-flow-shift. Defaults to the reference DMD2's range.", + ) + parser.add_argument( + "--dmd2-critic-loss-space", + type=str, + choices=["velocity", "x0"], + default="velocity", + help="Space of the DMD2 critic's flow-matching loss: velocity, or x0 = x_sigma - sigma * v, " + "which weights the velocity MSE by sigma^2.", + ) + parser.add_argument( + "--critic-load", + type=str, + default=None, + help="HF pipeline checkpoint the DMD2 critic starts from. Defaults to --teacher-load.", + ) + parser.add_argument( + "--critic-lr", + type=float, + default=None, + help="Learning rate of the DMD2 critic. Defaults to --lr.", + ) parser.add_argument( "--advantage-estimator", type=str, @@ -1765,6 +1807,16 @@ def set_default_diffusion_args(args) -> None: 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: + args.custom_expand_samples_to_train_pairs_path = ( + "miles.ray.data_conversion_hub.dmd2.expand_samples_to_train_pairs" + ) + if args.critic_load is None: + args.critic_load = args.teacher_load + if args.critic_lr is None: + args.critic_lr = args.lr + if args.ref_mode is None: args.ref_mode = "lora_base" if args.diffusion_kl_beta > 0 else "none" @@ -1907,6 +1959,52 @@ def validate_train_sde_backend(args) -> None: ) +def validate_dmd2_args(args) -> None: + if args.loss_type != "dmd2": + if args.critic_load is not None or args.critic_lr is not None: + raise ValueError("--critic-load and --critic-lr configure the critic group of --loss-type dmd2") + return + if args.teacher_load is None: + raise ValueError("--loss-type dmd2 requires --teacher-load to score the student's samples") + if args.dmd2_teacher_guidance_scale is None or args.dmd2_teacher_guidance_scale < 1: + raise ValueError( + f"--loss-type dmd2 requires --dmd2-teacher-guidance-scale >= 1, got {args.dmd2_teacher_guidance_scale}" + ) + if args.fsdp_flow_shift is None or "visual" not in args.fsdp_flow_shift: + raise ValueError("--loss-type dmd2 requires a visual --fsdp-flow-shift for the critic's sigma grid") + min_sigma, max_sigma = args.dmd2_score_sigma_range + if not 0 <= min_sigma < max_sigma <= 1: + raise ValueError(f"--dmd2-score-sigma-range needs 0 <= MIN < MAX <= 1, got {min_sigma} {max_sigma}") + if args.diffusion_guidance_scale != 1.0 or args.diffusion_true_cfg_scale is not None: + raise ValueError( + "--loss-type dmd2 samples the student unguided; set --diffusion-guidance-scale 1.0 " + "and drop --diffusion-true-cfg-scale" + ) + if args.use_lora or args.teacher_lora_adapter_paths is not None: + raise ValueError( + "--loss-type dmd2 trains the full student and critic; drop --use-lora and --teacher-lora-adapter-path" + ) + if args.ref_mode != "none": + raise ValueError("--loss-type dmd2 uses no reference model; drop --ref-mode and --diffusion-kl-beta") + if args.custom_prepare_train_batch_path is None or args.custom_loss_function_path is None: + raise ValueError( + "--loss-type dmd2 has no built-in generator loss yet; pass --custom-prepare-train-batch-path " + "and --custom-loss-function-path" + ) + if args.num_steps_per_rollout != 1: + raise ValueError( + f"--loss-type dmd2 takes one actor step per rollout, got --num-steps-per-rollout " + f"{args.num_steps_per_rollout}; the critic scores each rollout once, for that step" + ) + dp_size = args.actor_num_gpus_per_node * args.actor_num_nodes // args.sequence_parallel_size + critic_steps = args.dmd2_critic_steps_per_rollout + if critic_steps < 1 or args.global_batch_size % (critic_steps * dp_size) != 0: + raise ValueError( + f"--dmd2-critic-steps-per-rollout {critic_steps} must be >= 1 and split each of the {dp_size} DP " + f"shards of the {args.global_batch_size} samples per rollout evenly" + ) + + def miles_validate_args(args): args.eval_datasets = _resolve_eval_datasets(args) @@ -2243,6 +2341,8 @@ def miles_validate_args(args): samples_per_rollout = args.rollout_batch_size * args.n_samples_per_prompt args.num_steps_per_rollout = max(1, samples_per_rollout // args.global_batch_size) + validate_dmd2_args(args) + if args.n_samples_per_prompt == 1: args.grpo_std_normalization = False logger.info("n_samples_per_prompt is set to 1, grpo_std_normalization will be set to False.") diff --git a/miles/utils/trainer_config.py b/miles/utils/trainer_config.py index d0f19408a..69966bf88 100644 --- a/miles/utils/trainer_config.py +++ b/miles/utils/trainer_config.py @@ -11,7 +11,25 @@ class TrainerConfig: def compute_trainer_configs(args: Namespace) -> list[TrainerConfig]: - return [TrainerConfig(role="actor")] + if args.loss_type != "dmd2": + return [TrainerConfig(role="actor")] + critic_steps = args.dmd2_critic_steps_per_rollout + critic_overrides = { + "hf_checkpoint": args.critic_load, + "lr": args.critic_lr, + # A sibling dir, as upstream's --critic-save: sharing one would clobber the actor's iteration tracker. + "load": None if args.load is None else args.load.rstrip("/") + "_critic", + "save": None if args.save is None else args.save.rstrip("/") + "_critic", + "num_steps_per_rollout": critic_steps, + "global_batch_size": args.global_batch_size // critic_steps, + "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_output_function_path": "miles.backends.fsdp_utils.loss_hub.dmd2.score_last_step_samples", + } + return [ + TrainerConfig(role="critic", overrides=critic_overrides), + TrainerConfig(role="actor", overrides={"teacher_load": None}), + ] def compute_trainer_args(args: Namespace, trainer: TrainerConfig) -> Namespace: diff --git a/tests/fast/backends/fsdp_utils/test_loss_hub_dmd2.py b/tests/fast/backends/fsdp_utils/test_loss_hub_dmd2.py new file mode 100644 index 000000000..32228c3a2 --- /dev/null +++ b/tests/fast/backends/fsdp_utils/test_loss_hub_dmd2.py @@ -0,0 +1,310 @@ +"""DMD2 critic-group hooks: the critic (fake score) and the frozen teacher share this group; the actor holds the student. + + rollout pair: x0 = the student's x0 prediction at its stop step i, denoising_env = the rollout cond + │ + prepare_critic_batch ──► prepare_sft_batch on {"latent": {"visual": x0}, "cond_kwargs": prepared pos cond} + (the critic's K steps are the SFT loss on the student's samples; the last step, + whose samples get scored, draws grid points whose unshifted sigma lies in + --dmd2-score-sigma-range, default [0.02, 0.98]) + │ + critic_loss_formula ──► sft_loss_formula on v, or on x0 = x_s - sigma v under --dmd2-critic-loss-space x0; + on the last step it also keeps, per micro-batch, + x_s = that step's noisy input, sigma, and x0_fake = x_s - sigma v_fake from the + training forward, i.e. the critic before the last update + │ + score_last_step_samples, without grad after the critic's steps, per kept micro-batch: + teacher, CFG --dmd2-teacher-guidance-scale over the rollout's neg cond ──► x0_real = x_s - sigma v_real + ──► {sample_index: {"x0_real", "x0_fake"}}; the teacher is resharded so sleep moves its shards + +What each test pins: + test_critic_batch_is_the_sft_batch_on_the_student_x0 earlier steps: inputs and targets == SFT on (x0, pos cond) + test_last_step_draws_from_the_scoring_range last step: the same SFT draw over grid points [20, 980] + test_score_sigma_range_bounds_the_unshifted_sigma a custom range bounds the unshifted sigma, not 1 - sigma + test_critic_loss_is_the_sft_loss loss and metrics == sft_loss_formula on every step + test_x0_critic_loss_weights_the_velocity_mse x0 loss == x0 MSE == sigma^2 * velocity MSE, input intact + test_only_the_last_step_keeps_scoring_inputs earlier steps keep nothing, so only the last step is scored + test_scores_match_separate_forwards_at_the_kept_input fused scores == critic and teacher forwards run apart at x_s + test_teacher_runs_cfg_and_the_critic_runs_unguided CFG combine for the teacher only + test_teacher_cfg_needs_the_rollout_negative_cond rejected instead of a forward without text + test_scoring_reshards_the_teacher teacher resharded after its no-grad forwards +""" + +from tests.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=10, suite="stage-a-cpu", labels=[]) + +from argparse import Namespace + +import pytest +import torch +import torch.nn as nn + +import miles.backends.fsdp_utils.loss_hub.dmd2 as dmd2 +from miles.backends.fsdp_utils.configs.sd3 import SD3TrainPipelineConfig +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, FlowNoiseSchedule +from miles.utils.types import CondKwargs, DenoisingEnv + +FLOW_SHIFT = 3.0 +LATENT_SHAPE = (2, 4, 4) +CRITIC_STEPS = 3 + + +class _CondVelocity(nn.Module): + """v = scale * mean(text embedding) per sample, so a prediction reveals which cond it saw.""" + + def __init__(self, scale): + super().__init__() + self.scale = scale + + def forward(self, hidden_states, timestep, return_dict, encoder_hidden_states, pooled_projections): + text = encoder_hidden_states.mean(dim=(1, 2)).view(-1, 1, 1, 1) + return (self.scale * text.expand_as(hidden_states),) + + +class _NoisyInputVelocity(nn.Module): + """v = x_s + timestep, so x0 = x_s - sigma v depends on both inputs.""" + + def forward(self, hidden_states, timestep, return_dict, **cond): + return (hidden_states + timestep.view(-1, 1, 1, 1),) + + +class _Metrics: + def __init__(self): + self.seen = {} + + def emit_mean(self, key, *, total, count): + prev_total, prev_count = self.seen.get(key, (0.0, 0)) + self.seen[key] = (prev_total + float(total), prev_count + count) + + +def _cond(value): + return CondKwargs(encoder_hidden_states=[torch.full((1, 3, 8), value)], pooled_projections=[torch.zeros(1, 8)]) + + +def _pairs(num_pairs, with_neg=True): + return [ + { + "x0": torch.randn(LATENT_SHAPE, generator=torch.Generator().manual_seed(n)), + "denoising_env": DenoisingEnv( + pos_cond_kwargs=_cond(1.0 + n), neg_cond_kwargs=_cond(-1.0) if with_neg else None + ), + "sample_index": 100 + n, + } + for n in range(num_pairs) + ] + + +def _ctx(teacher_guidance_scale=3.0, critic_scale=1.0, teacher_scale=1.0): + return DiffusionLossContext( + models={"transformer": _CondVelocity(critic_scale)}, + teacher_models={"transformer": _CondVelocity(teacher_scale)}, + train_pipeline_config=SD3TrainPipelineConfig(), + sde_backend=None, + args=Namespace( + seed=7, + micro_batch_size=2, + num_steps_per_rollout=CRITIC_STEPS, + fsdp_flow_shift={"visual": FLOW_SHIFT}, + fsdp_supervised_streams=["visual"], + log_loss_sigma_bucket=0, + dmd2_teacher_guidance_scale=teacher_guidance_scale, + dmd2_score_sigma_range=[0.02, 0.98], + dmd2_critic_loss_space="velocity", + ), + forward_dtype=torch.float32, + device=torch.device("cpu"), + rollout_id=4, + dp_rank=1, + ) + + +def _critic_step(ctx, pairs, optim_step_idx, metrics=None): + """One critic optimizer step as _train_core runs it: prepare, the critic's training forward, the loss hook.""" + ctx.optim_step_idx = optim_step_idx + steps = [] + for start in range(0, len(pairs), ctx.args.micro_batch_size): + batch = pairs[start : start + ctx.args.micro_batch_size] + ctx.microbatch_id = optim_step_idx * 10 + start + prepared = dmd2.prepare_critic_batch(ctx, batch) + new_pred = ctx.train_pipeline_config.compute_noise_pred( + model=prepared.model, + latents_input=prepared.latents, + timesteps_input=prepared.timesteps_for_model, + pos_cond=prepared.pos_cond, + neg_cond=None, + joint_cond=None, + use_cfg=prepared.use_cfg, + cfg_batching=prepared.cfg_batching, + guidance_scale=prepared.guidance_scale, + true_cfg_scale=None, + ) + loss = dmd2.critic_loss_formula( + ctx, batch, prepared, new_pred=new_pred, old_pred=None, ref_pred=None, metrics=metrics or _Metrics() + ) + steps.append((batch, prepared, new_pred, loss)) + return steps + + +def _sft_pairs(ctx, pairs): + config = ctx.train_pipeline_config + return [ + { + "latent": {"visual": pair["x0"]}, + "cond_kwargs": config.prepare_cond_kwargs(pair["denoising_env"].pos_cond_kwargs, ctx.device), + } + for pair in pairs + ] + + +def test_critic_batch_is_the_sft_batch_on_the_student_x0(): + ctx = _ctx() + pairs = _pairs(3) + + for optim_step_idx in range(CRITIC_STEPS - 1): + ctx.optim_step_idx = optim_step_idx + critic_batch = dmd2.prepare_critic_batch(ctx, pairs) + sft_batch = prepare_sft_batch(ctx, _sft_pairs(ctx, pairs)) + + assert critic_batch.model is ctx.models["transformer"] + for field in ("latents", "timesteps", "timesteps_for_model"): + assert torch.equal(getattr(critic_batch, field)["visual"], getattr(sft_batch, field)["visual"]) + assert torch.equal(critic_batch.extras["target"]["visual"], sft_batch.extras["target"]["visual"]) + assert torch.equal(critic_batch.pos_cond["encoder_hidden_states"], sft_batch.pos_cond["encoder_hidden_states"]) + assert not critic_batch.use_cfg + + +def test_last_step_draws_from_the_scoring_range(): + ctx = _ctx() + pairs = _pairs(256) + ctx.optim_step_idx = CRITIC_STEPS - 1 + + critic_batch = dmd2.prepare_critic_batch(ctx, pairs) + sft_batch = prepare_sft_batch(ctx, _sft_pairs(ctx, pairs), grid_index_range=(20, 980)) + + assert torch.equal(critic_batch.latents["visual"], sft_batch.latents["visual"]) + assert torch.equal(critic_batch.extras["target"]["visual"], sft_batch.extras["target"]["visual"]) + grid = FlowNoiseSchedule.shifted(FLOW_SHIFT, 1000).sigmas + sigmas = critic_batch.extras["sigmas"]["visual"] + assert set(sigmas.tolist()) <= set(grid[20:981].tolist()) + # The same draw without the range leaves it, so the restriction is exercised. + assert not set(prepare_sft_batch(ctx, _sft_pairs(ctx, pairs)).extras["sigmas"]["visual"].tolist()) <= set( + grid[20:981].tolist() + ) + + +def test_score_sigma_range_bounds_the_unshifted_sigma(): + ctx = _ctx() + ctx.args.dmd2_score_sigma_range = [0.1, 0.5] + pairs = _pairs(256) + ctx.optim_step_idx = CRITIC_STEPS - 1 + + critic_batch = dmd2.prepare_critic_batch(ctx, pairs) + # Grid index i carries the unshifted sigma 1 - i / 1000, so [0.1, 0.5] is grid points [500, 900]. + sft_batch = prepare_sft_batch(ctx, _sft_pairs(ctx, pairs), grid_index_range=(500, 900)) + + sigmas = critic_batch.extras["sigmas"]["visual"] + assert torch.equal(sigmas, sft_batch.extras["sigmas"]["visual"]) + unshifted = sigmas / (FLOW_SHIFT - (FLOW_SHIFT - 1) * sigmas) + assert unshifted.min() >= 0.1 - 1e-6 and unshifted.max() <= 0.5 + 1e-6 + + +def test_critic_loss_is_the_sft_loss(): + for optim_step_idx in range(CRITIC_STEPS): + ctx = _ctx() + metrics = _Metrics() + sft_metrics = _Metrics() + for batch, prepared, new_pred, loss in _critic_step(ctx, _pairs(3), optim_step_idx, metrics): + sft_loss = sft_loss_formula( + ctx, batch, prepared, new_pred=new_pred, old_pred=None, ref_pred=None, metrics=sft_metrics + ) + assert torch.equal(loss, sft_loss) + assert metrics.seen == sft_metrics.seen + + +def test_x0_critic_loss_weights_the_velocity_mse(): + for optim_step_idx in range(CRITIC_STEPS): + ctx = _ctx() + ctx.models["transformer"] = _NoisyInputVelocity() + ctx.args.dmd2_critic_loss_space = "x0" + for batch, prepared, new_pred, loss in _critic_step(ctx, _pairs(3), optim_step_idx): + x_s = prepared.latents["visual"] + sigma = prepared.extras["sigmas"]["visual"].view(-1, 1, 1, 1) + x0 = torch.stack([pair["x0"] for pair in batch]) + x0_mse = (x_s - sigma * new_pred["visual"] - x0).square().flatten(1).mean(dim=1) + velocity_mse = (new_pred["visual"] - prepared.extras["target"]["visual"]).square().flatten(1).mean(dim=1) + torch.testing.assert_close(loss, x0_mse.sum()) + torch.testing.assert_close(loss, (sigma.flatten() ** 2 * velocity_mse).sum()) + + +def test_only_the_last_step_keeps_scoring_inputs(): + ctx = _ctx() + pairs = _pairs(9) + + for optim_step_idx in range(CRITIC_STEPS - 1): + _critic_step(ctx, pairs[optim_step_idx * 3 : optim_step_idx * 3 + 3], optim_step_idx) + assert ctx.train_output_inputs == [] + + _critic_step(ctx, pairs[6:], CRITIC_STEPS - 1) + scores = dmd2.score_last_step_samples(ctx, pairs) + + assert list(scores) == [106, 107, 108] + + +def test_scores_match_separate_forwards_at_the_kept_input(): + ctx = _ctx(teacher_guidance_scale=3.0) + ctx.models["transformer"] = _NoisyInputVelocity() + pairs = _pairs(5) + + steps = _critic_step(ctx, pairs, CRITIC_STEPS - 1) + scores = dmd2.score_last_step_samples(ctx, pairs) + + assert list(scores) == [100, 101, 102, 103, 104] + for batch, prepared, _, _ in steps: + x_s = prepared.latents["visual"] + timesteps = prepared.timesteps["visual"] + sigma = prepared.extras["sigmas"]["visual"].view(-1, 1, 1, 1) + fake = dmd2._predict_velocity(ctx, ctx.models["transformer"], batch, x_s, timesteps, 1.0) + real = dmd2._predict_velocity(ctx, ctx.teacher_models["transformer"], batch, x_s, timesteps, 3.0) + for n, pair in enumerate(batch): + assert torch.equal(scores[pair["sample_index"]]["x0_fake"], x_s[n] - sigma[n] * fake[n]) + assert torch.equal(scores[pair["sample_index"]]["x0_real"], x_s[n] - sigma[n] * real[n]) + + +def test_teacher_runs_cfg_and_the_critic_runs_unguided(): + ctx = _ctx(teacher_guidance_scale=3.0, teacher_scale=1.0, critic_scale=2.0) + pairs = _pairs(2) + + [(_, prepared, _, _)] = _critic_step(ctx, pairs, CRITIC_STEPS - 1) + scores = dmd2.score_last_step_samples(ctx, pairs) + + x_s = prepared.latents["visual"] + sigma = prepared.extras["sigmas"]["visual"].view(-1, 1, 1, 1) + for n, pair in enumerate(pairs): + pos, neg = 1.0 + n, -1.0 + torch.testing.assert_close( + scores[pair["sample_index"]]["x0_real"], x_s[n] - sigma[n] * (neg + 3.0 * (pos - neg)) + ) + torch.testing.assert_close(scores[pair["sample_index"]]["x0_fake"], x_s[n] - sigma[n] * 2.0 * pos) + + +def test_teacher_cfg_needs_the_rollout_negative_cond(): + ctx = _ctx(teacher_guidance_scale=3.0) + _critic_step(ctx, _pairs(2, with_neg=False), CRITIC_STEPS - 1) + with pytest.raises(ValueError, match="needs the rollout's negative cond"): + dmd2.score_last_step_samples(ctx, _pairs(2, with_neg=False)) + # Unguided, the teacher reads only the positive cond. + ctx = _ctx(teacher_guidance_scale=1.0) + _critic_step(ctx, _pairs(2, with_neg=False), CRITIC_STEPS - 1) + dmd2.score_last_step_samples(ctx, _pairs(2, with_neg=False)) + + +def test_scoring_reshards_the_teacher(monkeypatch): + resharded = [] + monkeypatch.setattr(dmd2, "reshard_model", resharded.append) + ctx = _ctx() + _critic_step(ctx, _pairs(2), CRITIC_STEPS - 1) + + dmd2.score_last_step_samples(ctx, _pairs(2)) + + assert resharded == [ctx.teacher_models["transformer"]] diff --git a/tests/fast/rollout/test_dmd2_convert.py b/tests/fast/rollout/test_dmd2_convert.py new file mode 100644 index 000000000..3d953a144 --- /dev/null +++ b/tests/fast/rollout/test_dmd2_convert.py @@ -0,0 +1,68 @@ +"""DMD2 rollout samples -> train pairs. + + stop_at_random_step request (stop = i, return [i, i+1]) ──► engine runs steps 0..i, step i goes to sigma 0 + dit_trajectory.latents [x_i, x0_i] (x0_i = the student's x0 prediction at step i) + dit_trajectory.latent_step_indices [i, i+1] + dit_trajectory.sigmas [sigma_0 .. sigma_i, 0] + │ + expand_samples_to_train_pairs ──► one pair per sample: + latent = x_i, x0 = x0_i, timestep = timesteps[i], sigma = sigma_i, step_index = i, + denoising_env, sample_index, prompt; rewards are ignored + A trajectory that did not stop at its first returned step is rejected. +""" + +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 miles.ray.data_conversion_hub.dmd2 import expand_samples_to_train_pairs +from miles.utils.types import DenoisingEnv, DiTTrajectory, Sample + +FULL_SIGMAS = [1.0, 0.75, 0.5, 0.25, 0.0] +FULL_TIMESTEPS = [1000.0, 750.0, 500.0, 250.0] + + +def _stopped_sample(index, step): + return Sample( + index=index, + prompt=f"prompt {index}", + denoising_env=DenoisingEnv(), + dit_trajectory=DiTTrajectory( + latents=torch.stack([torch.full((2, 3), float(index)), torch.full((2, 3), -float(index))]), + timesteps=torch.tensor(FULL_TIMESTEPS[: step + 1]), + sigmas=torch.tensor(FULL_SIGMAS[: step + 1] + [0.0]), + latent_step_indices=torch.tensor([step, step + 1]), + ), + ) + + +def test_each_stopped_sample_becomes_one_pair(): + samples = [_stopped_sample(10, 0), _stopped_sample(11, 2)] + + pairs = expand_samples_to_train_pairs(None, samples, [0.0, 0.0], [0.0, 0.0])["train_data"] + + assert [pair["sample_index"] for pair in pairs] == [10, 11] + assert [pair["step_index"] for pair in pairs] == [0, 2] + assert [pair["sigma"] for pair in pairs] == [1.0, 0.5] + assert [pair["timestep"] for pair in pairs] == [1000.0, 500.0] + assert torch.equal(pairs[1]["latent"], torch.full((2, 3), 11.0)) + assert torch.equal(pairs[1]["x0"], torch.full((2, 3), -11.0)) + assert pairs[1]["denoising_env"] is samples[1].denoising_env + assert pairs[1]["prompt"] == "prompt 11" + + +def test_full_trajectory_is_rejected(): + sample = _stopped_sample(10, 1) + sample.dit_trajectory.latent_step_indices = None + with pytest.raises(ValueError, match="stop_at_random_step"): + expand_samples_to_train_pairs(None, [sample], [0.0], [0.0]) + + +def test_trajectory_that_runs_past_its_returned_step_is_rejected(): + sample = _stopped_sample(10, 1) + sample.dit_trajectory.sigmas = torch.tensor(FULL_SIGMAS) + with pytest.raises(ValueError, match="stopped at its first returned step"): + expand_samples_to_train_pairs(None, [sample], [0.0], [0.0]) diff --git a/tests/fast/utils/test_dmd2_arguments.py b/tests/fast/utils/test_dmd2_arguments.py new file mode 100644 index 000000000..d493e3e90 --- /dev/null +++ b/tests/fast/utils/test_dmd2_arguments.py @@ -0,0 +1,117 @@ +"""--loss-type dmd2 validation: reject what the critic group and the one-step actor cannot run, never fill args. + + defaults ──► --critic-load = --teacher-load, --critic-lr = --lr, unless the user set them + 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 + other losses ──► --critic-load / --critic-lr have no consumer and are rejected + teacher score ──► CFG --dmd2-teacher-guidance-scale >= 1 + actor ──► unguided rollouts, one step per rollout, generator hooks given until a built-in lands +""" + +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 set_default_diffusion_args, validate_dmd2_args + + +def _args(**overrides): + values = dict( + loss_type="dmd2", + critic_load="teacher", + critic_lr=1e-6, + teacher_load="teacher", + teacher_lora_adapter_paths=None, + dmd2_teacher_guidance_scale=4.5, + dmd2_critic_steps_per_rollout=5, + dmd2_score_sigma_range=[0.02, 0.98], + fsdp_flow_shift={"visual": 3.0}, + diffusion_guidance_scale=1.0, + diffusion_true_cfg_scale=None, + use_lora=False, + ref_mode="none", + custom_prepare_train_batch_path="my.prepare_generator", + custom_loss_function_path="my.generator_loss", + num_steps_per_rollout=1, + global_batch_size=40, + actor_num_gpus_per_node=4, + actor_num_nodes=1, + sequence_parallel_size=2, + ) + values.update(overrides) + return Namespace(**values) + + +@pytest.mark.parametrize( + ("user", "expected"), + [({}, ("teacher", 2e-6)), ({"critic_load": "critic-init", "critic_lr": 8e-6}, ("critic-init", 8e-6))], +) +def test_dmd2_critic_defaults_to_the_teacher_and_the_actor_lr(user, expected): + args = Namespace( + sglang_tp_size=1, + sglang_sp_degree=None, + sglang_enable_cfg_parallel=False, + 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, + ref_mode=None, + diffusion_kl_beta=0.0, + teacher_load="teacher", + lr=2e-6, + **{"critic_load": None, "critic_lr": None, **user}, + ) + set_default_diffusion_args(args) + assert (args.critic_load, args.critic_lr) == expected + + +@pytest.mark.parametrize("flag", ["critic_load", "critic_lr"]) +def test_critic_flags_without_dmd2_are_rejected(flag): + with pytest.raises(ValueError, match="configure the critic group of --loss-type dmd2"): + validate_dmd2_args(Namespace(**{"loss_type": "nft", "critic_load": None, "critic_lr": None, flag: "set"})) + validate_dmd2_args(Namespace(loss_type="nft", critic_load=None, critic_lr=None)) + + +def test_valid_dmd2_args_pass_unchanged(): + args = _args() + original = vars(args).copy() + validate_dmd2_args(args) + assert vars(args) == original + + +@pytest.mark.parametrize( + ("overrides", "message"), + [ + ({"teacher_load": None}, "requires --teacher-load"), + ({"dmd2_teacher_guidance_scale": None}, "--dmd2-teacher-guidance-scale >= 1"), + ({"dmd2_teacher_guidance_scale": 0.5}, "--dmd2-teacher-guidance-scale >= 1"), + ({"fsdp_flow_shift": None}, "visual --fsdp-flow-shift"), + ({"fsdp_flow_shift": {"audio": 3.0}}, "visual --fsdp-flow-shift"), + ({"dmd2_score_sigma_range": [0.5, 0.5]}, "0 <= MIN < MAX <= 1"), + ({"dmd2_score_sigma_range": [0.9, 0.1]}, "0 <= MIN < MAX <= 1"), + ({"dmd2_score_sigma_range": [-0.1, 0.5]}, "0 <= MIN < MAX <= 1"), + ({"dmd2_score_sigma_range": [0.5, 1.5]}, "0 <= MIN < MAX <= 1"), + ({"diffusion_guidance_scale": 4.5}, "samples the student unguided"), + ({"diffusion_true_cfg_scale": 4.5}, "samples the student unguided"), + ({"use_lora": True}, "drop --use-lora"), + ({"teacher_lora_adapter_paths": ["teacher-adapter"]}, "drop --use-lora and --teacher-lora-adapter-path"), + ({"ref_mode": "ref"}, "uses no reference model"), + ({"custom_loss_function_path": None}, "no built-in generator loss yet"), + ({"num_steps_per_rollout": 2}, "one actor step per rollout"), + ({"dmd2_critic_steps_per_rollout": 0}, "must be >= 1"), + # 40 samples over 2 DP shards = 20 per shard, which 3 critic steps cannot split. + ({"dmd2_critic_steps_per_rollout": 3}, "split each of the 2 DP shards"), + ], +) +def test_unsupported_dmd2_args_are_rejected(overrides, message): + args = _args(**overrides) + original = vars(args).copy() + with pytest.raises(ValueError, match=message): + validate_dmd2_args(args) + assert vars(args) == original diff --git a/tests/fast/utils/test_trainer_config.py b/tests/fast/utils/test_trainer_config.py index e1959b808..7b28a3d40 100644 --- a/tests/fast/utils/test_trainer_config.py +++ b/tests/fast/utils/test_trainer_config.py @@ -27,3 +27,39 @@ def test_trainer_args_apply_overrides_to_a_deep_copy(): def test_trainer_args_reject_unknown_overrides(): with pytest.raises(AssertionError, match="overrides 'lrr'"): compute_trainer_args(Namespace(lr=1e-5), TrainerConfig(role="critic", overrides={"lrr": 8e-6})) + + +@pytest.mark.parametrize( + ("load", "save", "critic_dir"), [("/ckpt/run/", "/ckpt/run", "/ckpt/run_critic"), (None, None, None)] +) +def test_dmd2_critic_trains_first_from_its_own_checkpoint(load, save, critic_dir): + args = Namespace( + loss_type="dmd2", + hf_checkpoint="student", + teacher_load="teacher", + critic_load="critic-init", + lr=2e-6, + critic_lr=8e-6, + load=load, + save=save, + global_batch_size=40, + num_steps_per_rollout=1, + dmd2_critic_steps_per_rollout=5, + custom_prepare_train_batch_path="my.prepare_generator", + custom_loss_function_path="my.generator_loss", + custom_train_output_function_path=None, + ) + original = vars(args).copy() + + trainer_configs = compute_trainer_configs(args) + + 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.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_output_function_path.endswith("loss_hub.dmd2.score_last_step_samples") + assert vars(actor) == {**original, "teacher_load": None} + assert vars(args) == original From f8cb580797589bdde148734b363f59f284c97aed Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Mon, 19 Oct 2026 23:12:03 +0000 Subject: [PATCH 08/33] feat(dmd2): train the student with the distribution matching gradient from the critic group's scores --- docs/user-guide/cli-reference.md | 2 +- docs/user-guide/customization.md | 5 +- miles/backends/fsdp_utils/loss_hub/dmd2.py | 83 +++++++- miles/backends/fsdp_utils/metrics.py | 4 + miles/utils/arguments.py | 19 +- miles/utils/trainer_config.py | 1 + .../backends/fsdp_utils/test_loss_hub_dmd2.py | 179 +++++++++++++++++- tests/fast/utils/test_dmd2_arguments.py | 42 +++- tests/fast/utils/test_trainer_config.py | 2 + 9 files changed, 320 insertions(+), 17 deletions(-) diff --git a/docs/user-guide/cli-reference.md b/docs/user-guide/cli-reference.md index 386de7b9d..8e616c814 100644 --- a/docs/user-guide/cli-reference.md +++ b/docs/user-guide/cli-reference.md @@ -284,7 +284,7 @@ See [Dtype Control](../advanced/dtype-control.md). | `--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`. | | `--no-diffusion-nft-adaptive-weight` | flag | off | | -| `--dmd2-critic-steps-per-rollout` | int | `5` | Critic optimizer steps per rollout under `dmd2`, before the actor's single step. Each DP shard must split into this many steps. The last step's samples are scored by the critic before that step's update. | +| `--dmd2-critic-steps-per-rollout` | int | `5` | Critic optimizer steps per rollout under `dmd2`, before the actor's single step. Each DP shard must split into this many steps. The last step's samples are scored by the critic before that step's update, and the actor trains on them only. | | `--dmd2-teacher-guidance-scale` | float | – | Required by `dmd2`: the teacher's CFG scale when scoring the student's samples; `1` runs it unguided. | | `--dmd2-score-sigma-range` | float float | `0.02 0.98` | `MIN MAX` of the unshifted sigma at which `dmd2` scores the student's samples: the last critic step draws grid points in this range and reads them through the visual `--fsdp-flow-shift`. The default is the reference DMD2 range. | | `--dmd2-critic-loss-space` | str | `velocity` | `velocity` or `x0`: the space of the critic's flow-matching loss. `x0` regresses x0 = x_σ − σ·v, which weights the velocity MSE by σ². | diff --git a/docs/user-guide/customization.md b/docs/user-guide/customization.md index 313c015b6..cdc441dcf 100644 --- a/docs/user-guide/customization.md +++ b/docs/user-guide/customization.md @@ -234,7 +234,7 @@ def buffer_filter( | `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` | 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. @@ -244,6 +244,9 @@ before the actor on each rollout: it starts from `--critic-load` (default `--tea 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. DiT forward always stays in the FSDP actor; the loss hook only computes the objective. diff --git a/miles/backends/fsdp_utils/loss_hub/dmd2.py b/miles/backends/fsdp_utils/loss_hub/dmd2.py index 001690a78..2746b5f48 100644 --- a/miles/backends/fsdp_utils/loss_hub/dmd2.py +++ b/miles/backends/fsdp_utils/loss_hub/dmd2.py @@ -1,4 +1,4 @@ -"""DMD2 critic-group hooks: the critic (fake score) learns the student's samples and scores those of its last step.""" +"""DMD2 hooks: the critic group learns and scores the student's samples; the actor follows the scores.""" from __future__ import annotations @@ -10,6 +10,7 @@ from miles.backends.fsdp_utils.input_dtype_policy import apply_input_dtype_policy 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.backends.fsdp_utils.metrics import record_rollout_train_abs_diff from miles.utils.metric_buffer import MetricBuffer @@ -153,3 +154,83 @@ def _predict_velocity( true_cfg_scale=None, ) return pred["visual"].float() + + +def select_scored_pairs(ctx: DiffusionLossContext, train_pairs: list[dict]) -> list[dict]: + """The pairs of the critic's last step, which it scored; the actor trains on these only.""" + scores = ctx.external_data["critic"] + scored = [pair for pair in train_pairs if pair["sample_index"] in scores] + if len(scored) != len(scores): + raise ValueError( + f"the critic scored {len(scores)} samples, but only {len(scored)} of them are in this rank's train pairs" + ) + return scored + + +def prepare_generator_batch( + ctx: DiffusionLossContext, + batch: list[dict], + *, + pad_to_len: int | None = None, +) -> PreparedBatch: + """The student's step ``i`` on its own rollout input ``x_i``, unguided.""" + if len(ctx.models) != 1: + raise ValueError("DMD2 currently supports a single DiT component") + device = ctx.device + config = ctx.train_pipeline_config + component_name, model = next(iter(ctx.models.items())) + latents = torch.stack([pair["latent"] for pair in batch]).to(device=device, dtype=torch.float32) + timesteps = torch.tensor([pair["timestep"] for pair in batch], device=device, dtype=torch.float32) + sigmas = torch.tensor([pair["sigma"] for pair in batch], device=device, dtype=torch.float32) + pos_list = [config.prepare_cond_kwargs(pair["denoising_env"].pos_cond_kwargs, device) for pair in batch] + # Rollout trajectories carry only the visual stream. + return PreparedBatch( + latents={"visual": latents}, + timesteps={"visual": timesteps}, + timesteps_for_model={"visual": config.process_timestep_as_input(timesteps)}, + model=model, + component_name=component_name, + guidance_scale=1.0, + use_cfg=False, + cfg_batching=False, + true_cfg_scale=None, + pos_cond=config.collate_cond_for_sample_batch(pos_list, device, pad_to_len=pad_to_len), + neg_cond=None, + joint_cond=None, + advantage=torch.ones(len(batch), device=device, dtype=torch.float32), + extras={"sigmas": sigmas}, + ) + + +def dmd2_loss_formula( + ctx: DiffusionLossContext, + batch: list[dict], + prepared: PreparedBatch, + *, + new_pred: dict[str, torch.Tensor], + old_pred: dict[str, torch.Tensor] | None, + ref_pred: dict[str, torch.Tensor] | None, + metrics: MetricBuffer, + write_old_log_prob: bool = False, + old_log_prob_from_new: bool = False, +) -> torch.Tensor: + """Distribution matching: x0's gradient is ``g / numel``, ``g = (x0_fake - x0_real) / mean|x0 - x0_real|``.""" + latents = prepared.latents["visual"] + sigmas = prepared.extras["sigmas"].view(len(batch), *([1] * (latents.ndim - 1))) + x0 = latents - sigmas * new_pred["visual"].float() + scores = ctx.external_data["critic"] + x0_real = torch.stack([scores[pair["sample_index"]]["x0_real"] for pair in batch]).to(x0.device) + x0_fake = torch.stack([scores[pair["sample_index"]]["x0_fake"] for pair in batch]).to(x0.device) + reduce_dims = tuple(range(1, x0.ndim)) + with torch.no_grad(): + grad = torch.nan_to_num((x0_fake - x0_real) / (x0 - x0_real).abs().mean(dim=reduce_dims, keepdim=True)) + per_pair = 0.5 * (x0 - (x0 - grad).detach()).square().mean(dim=reduce_dims) + loss_sum = per_pair.sum() + + with torch.no_grad(): + bsz = len(batch) + metrics.emit_mean("loss", total=loss_sum, count=bsz) + metrics.emit_mean("dmd2_grad_abs_mean", total=grad.abs().mean(dim=reduce_dims).sum(), count=bsz) + rollout_x0 = torch.stack([pair["x0"] for pair in batch]).to(device=x0.device, dtype=torch.float32) + record_rollout_train_abs_diff(metrics, "x0", x0, rollout_x0) + return loss_sum diff --git a/miles/backends/fsdp_utils/metrics.py b/miles/backends/fsdp_utils/metrics.py index 32b419398..b51f17d89 100644 --- a/miles/backends/fsdp_utils/metrics.py +++ b/miles/backends/fsdp_utils/metrics.py @@ -33,6 +33,10 @@ "nft_adv_mean": MetricReduce.MEAN, "nft_t_mean": MetricReduce.MEAN, "nft_num_timesteps": MetricReduce.MEAN, + "dmd2_grad_abs_mean": MetricReduce.MEAN, + "x0_mean_abs_diff": MetricReduce.MEAN, + "x0_max_abs_diff": MetricReduce.MAX, + "x0_rel_max": MetricReduce.MAX, } diff --git a/miles/utils/arguments.py b/miles/utils/arguments.py index 639b4f029..9303f101e 100644 --- a/miles/utils/arguments.py +++ b/miles/utils/arguments.py @@ -948,7 +948,8 @@ def add_algo_arguments(parser): 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 selects the DMD2 train-data converter and trains a critic group next to the actor. " + "dmd2 auto-fills the DMD2 converter / prepare / loss-formula / train-input paths and trains a " + "critic group before the actor. " "DiT forward always stays in the FSDP actor." ), ) @@ -1024,7 +1025,10 @@ def add_algo_arguments(parser): "--dmd2-critic-steps-per-rollout", type=int, default=5, - help="DMD2 critic optimizer steps per rollout, taken before the actor's single step (TTUR).", + help=( + "DMD2 critic optimizer steps per rollout, taken before the actor's single step (TTUR); " + "the critic scores its last step's samples and the actor trains on those only." + ), ) parser.add_argument( "--dmd2-teacher-guidance-scale", @@ -1816,6 +1820,12 @@ 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_function_path is None: + args.custom_train_input_function_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" @@ -1986,11 +1996,6 @@ def validate_dmd2_args(args) -> None: ) if args.ref_mode != "none": raise ValueError("--loss-type dmd2 uses no reference model; drop --ref-mode and --diffusion-kl-beta") - if args.custom_prepare_train_batch_path is None or args.custom_loss_function_path is None: - raise ValueError( - "--loss-type dmd2 has no built-in generator loss yet; pass --custom-prepare-train-batch-path " - "and --custom-loss-function-path" - ) if args.num_steps_per_rollout != 1: raise ValueError( f"--loss-type dmd2 takes one actor step per rollout, got --num-steps-per-rollout " diff --git a/miles/utils/trainer_config.py b/miles/utils/trainer_config.py index 69966bf88..0c14de646 100644 --- a/miles/utils/trainer_config.py +++ b/miles/utils/trainer_config.py @@ -24,6 +24,7 @@ def compute_trainer_configs(args: Namespace) -> list[TrainerConfig]: "global_batch_size": args.global_batch_size // critic_steps, "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_function_path": None, "custom_train_output_function_path": "miles.backends.fsdp_utils.loss_hub.dmd2.score_last_step_samples", } return [ diff --git a/tests/fast/backends/fsdp_utils/test_loss_hub_dmd2.py b/tests/fast/backends/fsdp_utils/test_loss_hub_dmd2.py index 32228c3a2..6aed8b941 100644 --- a/tests/fast/backends/fsdp_utils/test_loss_hub_dmd2.py +++ b/tests/fast/backends/fsdp_utils/test_loss_hub_dmd2.py @@ -1,4 +1,4 @@ -"""DMD2 critic-group hooks: the critic (fake score) and the frozen teacher share this group; the actor holds the student. +"""DMD2 hooks: the critic (fake score) and the frozen teacher share the critic group; the actor holds the student. rollout pair: x0 = the student's x0 prediction at its stop step i, denoising_env = the rollout cond │ @@ -15,6 +15,13 @@ score_last_step_samples, without grad after the critic's steps, per kept micro-batch: teacher, CFG --dmd2-teacher-guidance-scale over the rollout's neg cond ──► x0_real = x_s - sigma v_real ──► {sample_index: {"x0_real", "x0_fake"}}; the teacher is resharded so sleep moves its shards + │ ctx.external_data["critic"] on the paired actor rank + select_scored_pairs ──► the actor's train-input hook keeps only the scored pairs, i.e. the critic's last step + prepare_generator_batch ──► the student's unguided step i on the rollout input x_i + dmd2_loss_formula: + x0 = x_i - sigma_i v_student (with grad; the rollout's x0_i only feeds a metric) + g = nan_to_num((x0_fake - x0_real) / mean|x0 - x0_real|) per pair + loss = 0.5 mean((x0 - sg(x0 - g))^2) ──► d/dx0 = g / numel, the reference implementation's gradient What each test pins: test_critic_batch_is_the_sft_batch_on_the_student_x0 earlier steps: inputs and targets == SFT on (x0, pos cond) @@ -27,6 +34,13 @@ test_teacher_runs_cfg_and_the_critic_runs_unguided CFG combine for the teacher only test_teacher_cfg_needs_the_rollout_negative_cond rejected instead of a forward without text test_scoring_reshards_the_teacher teacher resharded after its no-grad forwards + test_actor_keeps_the_critic_last_step_pairs same shard ──► the actor trains on the scored 1/K only + test_scores_outside_the_shard_are_rejected a broken rank pairing fails instead of shrinking the batch + test_generator_batch_is_the_student_step_on_its_input x_i, t_i, sigma_i and the positive cond, no CFG + test_generator_needs_a_single_component multi-DiT families are rejected + test_surrogate_gradient_matches_the_reference same gradient as the reference's batch-mean MSE + test_critic_matching_the_teacher_gives_no_gradient x0_fake == x0_real ──► zero loss and gradient + test_gaussian_student_moves_toward_the_teacher analytic scores: sign and normalization move mu """ from tests.ci.ci_register import register_cpu_ci @@ -43,6 +57,8 @@ from miles.backends.fsdp_utils.configs.sd3 import SD3TrainPipelineConfig 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, FlowNoiseSchedule +from miles.backends.fsdp_utils.metrics import new_metric_buffer +from miles.utils.train_data_utils import build_microbatch_schedule from miles.utils.types import CondKwargs, DenoisingEnv FLOW_SHIFT = 3.0 @@ -308,3 +324,164 @@ def test_scoring_reshards_the_teacher(monkeypatch): dmd2.score_last_step_samples(ctx, _pairs(2)) assert resharded == [ctx.teacher_models["transformer"]] + + +def test_actor_keeps_the_critic_last_step_pairs(): + ctx = _ctx() + pairs = _pairs(9) + schedule = build_microbatch_schedule( + num_pairs_per_optim_step=3, num_optim_steps_per_rollout=CRITIC_STEPS, micro_batch_size=3 + ) + for optim_step_idx, [(pair_lo, pair_hi)] in enumerate(schedule): + _critic_step(ctx, pairs[pair_lo:pair_hi], optim_step_idx) + + actor_ctx = _ctx() + actor_ctx.external_data["critic"] = dmd2.score_last_step_samples(ctx, pairs) + + assert dmd2.select_scored_pairs(actor_ctx, pairs) == pairs[6:] + + +def test_scores_outside_the_shard_are_rejected(): + pairs = _pairs(4) + ctx = _ctx() + ctx.external_data["critic"] = {pair["sample_index"]: {} for pair in pairs[2:]} + with pytest.raises(ValueError, match="only 1 of them"): + dmd2.select_scored_pairs(ctx, pairs[:3]) + + +def _generator_pairs(num_pairs): + return [ + { + "latent": torch.randn(LATENT_SHAPE, generator=torch.Generator().manual_seed(n)).to(torch.bfloat16), + "x0": torch.zeros(LATENT_SHAPE), + "timestep": 750.0 - 250.0 * n, + "sigma": 0.75 - 0.25 * n, + "denoising_env": DenoisingEnv(pos_cond_kwargs=_cond(1.0 + n), neg_cond_kwargs=None), + "sample_index": 100 + n, + } + for n in range(num_pairs) + ] + + +def _metrics(): + return new_metric_buffer(None, torch.device("cpu"), ["transformer"]) + + +def _loss(ctx, pairs, x0): + """dmd2_loss_formula with the student predicting ``x0`` from each pair's rollout input.""" + prepared = dmd2.prepare_generator_batch(ctx, pairs) + sigmas = prepared.extras["sigmas"].view(-1, 1, 1, 1) + new_pred = {"visual": (prepared.latents["visual"] - x0) / sigmas} + metrics = _metrics() + return ( + dmd2.dmd2_loss_formula(ctx, pairs, prepared, new_pred=new_pred, old_pred=None, ref_pred=None, metrics=metrics), + metrics, + ) + + +def _scores(pairs, x0_real, x0_fake): + return { + pair["sample_index"]: {"x0_real": real, "x0_fake": fake} + for pair, real, fake in zip(pairs, x0_real, x0_fake, strict=True) + } + + +def test_generator_batch_is_the_student_step_on_its_input(): + ctx = _ctx() + pairs = _generator_pairs(2) + + prepared = dmd2.prepare_generator_batch(ctx, pairs) + + assert prepared.model is ctx.models["transformer"] + assert torch.equal(prepared.latents["visual"], torch.stack([pair["latent"] for pair in pairs]).float()) + assert prepared.timesteps["visual"].tolist() == [750.0, 500.0] + assert prepared.extras["sigmas"].tolist() == [0.75, 0.5] + assert prepared.pos_cond["encoder_hidden_states"][:, 0, 0].tolist() == [1.0, 2.0] + assert not prepared.use_cfg and prepared.neg_cond is None + + +def test_generator_needs_a_single_component(): + ctx = _ctx() + ctx.models["transformer_2"] = ctx.models["transformer"] + with pytest.raises(ValueError, match="single DiT component"): + dmd2.prepare_generator_batch(ctx, _generator_pairs(1)) + + +def test_surrogate_gradient_matches_the_reference(): + ctx = _ctx() + pairs = _generator_pairs(2) + x0 = torch.randn(2, *LATENT_SHAPE, requires_grad=True) + x0_real, x0_fake = torch.randn(2, *LATENT_SHAPE), torch.randn(2, *LATENT_SHAPE) + ctx.external_data = {"critic": _scores(pairs, x0_real, x0_fake)} + + loss_sum, _ = _loss(ctx, pairs, x0) + (loss_sum / len(pairs)).backward() + + # tianweiy/DMD2 compute_distribution_matching_loss, on the same x0 and predictions. + reference_x0 = x0.detach().clone().requires_grad_() + with torch.no_grad(): + p_real, p_fake = reference_x0 - x0_real, reference_x0 - x0_fake + grad = torch.nan_to_num((p_real - p_fake) / p_real.abs().mean(dim=[1, 2, 3], keepdim=True)) + torch.nn.functional.mse_loss(reference_x0, (reference_x0 - grad).detach(), reduction="mean").mul(0.5).backward() + + torch.testing.assert_close(x0.grad, reference_x0.grad) + + +def test_critic_matching_the_teacher_gives_no_gradient(): + ctx = _ctx() + pairs = _generator_pairs(2) + x0 = torch.randn(2, *LATENT_SHAPE, requires_grad=True) + x0_pred = torch.randn(2, *LATENT_SHAPE) + ctx.external_data = {"critic": _scores(pairs, x0_pred, x0_pred)} + + loss_sum, metrics = _loss(ctx, pairs, x0) + loss_sum.backward() + + assert float(loss_sum) == 0.0 + assert torch.count_nonzero(x0.grad) == 0 + assert metrics.reduce()["dmd2_grad_abs_mean"] == 0.0 + + +def test_gaussian_student_moves_toward_the_teacher(): + # Data N(mu, 1) per element, noised as x_s = a x + b eps: E[x | x_s] = mu + a (x_s - a mu) / (a^2 + b^2). + def posterior_mean(mu, x_s, a, b): + return mu + a * (x_s - a * mu) / (a**2 + b**2) + + ctx = _ctx() + pairs = _generator_pairs(2) + teacher_mu, student_mu = 1.0, torch.tensor(-1.0, requires_grad=True) + optimizer = torch.optim.SGD([student_mu], lr=0.5) + generator = torch.Generator().manual_seed(0) + gaps = [] + for _ in range(20): + optimizer.zero_grad() + x0 = student_mu + torch.randn(2, *LATENT_SHAPE, generator=generator) + a, b = 0.5, 0.5 + x_s = a * x0.detach() + b * torch.randn(x0.shape, generator=generator) + ctx.external_data = { + "critic": _scores( + pairs, + posterior_mean(teacher_mu, x_s, a, b), + posterior_mean(float(student_mu), x_s, a, b), + ) + } + loss_sum, _ = _loss(ctx, pairs, x0) + (loss_sum / len(pairs)).backward() + optimizer.step() + gaps.append(abs(teacher_mu - float(student_mu))) + + assert gaps == sorted(gaps, reverse=True) + assert gaps[-1] < 0.5 * gaps[0] + + +def test_trainer_and_rollout_x0_diff_is_recorded(): + ctx = _ctx() + pairs = _generator_pairs(2) + x0 = torch.stack([pair["x0"] for pair in pairs]) + 0.25 + ctx.external_data = {"critic": _scores(pairs, x0, x0)} + + _, metrics = _loss(ctx, pairs, x0) + + reduced = metrics.reduce() + assert reduced["x0_mean_abs_diff"] == pytest.approx(0.25) + assert reduced["x0_max_abs_diff"] == pytest.approx(0.25) diff --git a/tests/fast/utils/test_dmd2_arguments.py b/tests/fast/utils/test_dmd2_arguments.py index d493e3e90..f878644a1 100644 --- a/tests/fast/utils/test_dmd2_arguments.py +++ b/tests/fast/utils/test_dmd2_arguments.py @@ -1,12 +1,13 @@ -"""--loss-type dmd2 validation: reject what the critic group and the one-step actor cannot run, never fill args. +"""--loss-type dmd2 defaults and validation; validation rejects what DMD2 cannot run and never fills args. - defaults ──► --critic-load = --teacher-load, --critic-lr = --lr, unless the user set them + defaults ──► converter / generator prepare / generator loss / train-input paths, + --critic-load = --teacher-load, --critic-lr = --lr, unless the user set them 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 other losses ──► --critic-load / --critic-lr have no consumer and are rejected teacher score ──► CFG --dmd2-teacher-guidance-scale >= 1 - actor ──► unguided rollouts, one step per rollout, generator hooks given until a built-in lands + actor ──► unguided rollouts, one step per rollout """ from tests.ci.ci_register import register_cpu_ci @@ -35,8 +36,6 @@ def _args(**overrides): diffusion_true_cfg_scale=None, use_lora=False, ref_mode="none", - custom_prepare_train_batch_path="my.prepare_generator", - custom_loss_function_path="my.generator_loss", num_steps_per_rollout=1, global_batch_size=40, actor_num_gpus_per_node=4, @@ -61,6 +60,7 @@ def test_dmd2_critic_defaults_to_the_teacher_and_the_actor_lr(user, expected): custom_expand_samples_to_train_pairs_path=None, custom_prepare_train_batch_path=None, custom_loss_function_path=None, + custom_train_input_function_path=None, ref_mode=None, diffusion_kl_beta=0.0, teacher_load="teacher", @@ -78,6 +78,37 @@ 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): + args = Namespace( + sglang_tp_size=1, + sglang_sp_degree=None, + sglang_enable_cfg_parallel=False, + 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_function_path=None, + ref_mode=None, + diffusion_kl_beta=0.0, + teacher_load="teacher", + lr=2e-6, + critic_load=None, + critic_lr=None, + ) + 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_function_path.endswith("loss_hub.dmd2.select_scored_pairs") + assert args.ref_mode == "none" + + def test_valid_dmd2_args_pass_unchanged(): args = _args() original = vars(args).copy() @@ -102,7 +133,6 @@ def test_valid_dmd2_args_pass_unchanged(): ({"use_lora": True}, "drop --use-lora"), ({"teacher_lora_adapter_paths": ["teacher-adapter"]}, "drop --use-lora and --teacher-lora-adapter-path"), ({"ref_mode": "ref"}, "uses no reference model"), - ({"custom_loss_function_path": None}, "no built-in generator loss yet"), ({"num_steps_per_rollout": 2}, "one actor step per rollout"), ({"dmd2_critic_steps_per_rollout": 0}, "must be >= 1"), # 40 samples over 2 DP shards = 20 per shard, which 3 critic steps cannot split. diff --git a/tests/fast/utils/test_trainer_config.py b/tests/fast/utils/test_trainer_config.py index 7b28a3d40..e8b8de87e 100644 --- a/tests/fast/utils/test_trainer_config.py +++ b/tests/fast/utils/test_trainer_config.py @@ -47,6 +47,7 @@ def test_dmd2_critic_trains_first_from_its_own_checkpoint(load, save, critic_dir dmd2_critic_steps_per_rollout=5, custom_prepare_train_batch_path="my.prepare_generator", custom_loss_function_path="my.generator_loss", + custom_train_input_function_path="my.select_pairs", custom_train_output_function_path=None, ) original = vars(args).copy() @@ -60,6 +61,7 @@ def test_dmd2_critic_trains_first_from_its_own_checkpoint(load, save, critic_dir assert (critic.num_steps_per_rollout, critic.global_batch_size) == (5, 8) 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_function_path is None assert critic.custom_train_output_function_path.endswith("loss_hub.dmd2.score_last_step_samples") assert vars(actor) == {**original, "teacher_load": None} assert vars(args) == original From 0c30c25201a9479d7fb54dcf401df286f1bfbbbb Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Tue, 10 Nov 2026 08:53:33 +0000 Subject: [PATCH 09/33] fix(dmd2): follow the train-input hook rename in the DMD2 defaults #338 renamed the hook to --custom-train-input-postprocess-path; the DMD2 defaults and the critic override still set custom_train_input_function_path, so --loss-type dmd2 failed in parse_args. Co-Authored-By: Claude Mythos 5.1 --- miles/utils/arguments.py | 4 ++-- miles/utils/trainer_config.py | 2 +- tests/fast/utils/test_dmd2_arguments.py | 6 +++--- tests/fast/utils/test_trainer_config.py | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/miles/utils/arguments.py b/miles/utils/arguments.py index 9303f101e..a8a79afa8 100644 --- a/miles/utils/arguments.py +++ b/miles/utils/arguments.py @@ -1824,8 +1824,8 @@ def set_default_diffusion_args(args) -> 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_function_path is None: - args.custom_train_input_function_path = "miles.backends.fsdp_utils.loss_hub.dmd2.select_scored_pairs" + 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" diff --git a/miles/utils/trainer_config.py b/miles/utils/trainer_config.py index 0c14de646..6d1636479 100644 --- a/miles/utils/trainer_config.py +++ b/miles/utils/trainer_config.py @@ -24,7 +24,7 @@ def compute_trainer_configs(args: Namespace) -> list[TrainerConfig]: "global_batch_size": args.global_batch_size // critic_steps, "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_function_path": None, + "custom_train_input_postprocess_path": None, "custom_train_output_function_path": "miles.backends.fsdp_utils.loss_hub.dmd2.score_last_step_samples", } return [ diff --git a/tests/fast/utils/test_dmd2_arguments.py b/tests/fast/utils/test_dmd2_arguments.py index f878644a1..15fb5c0b1 100644 --- a/tests/fast/utils/test_dmd2_arguments.py +++ b/tests/fast/utils/test_dmd2_arguments.py @@ -60,7 +60,7 @@ def test_dmd2_critic_defaults_to_the_teacher_and_the_actor_lr(user, expected): custom_expand_samples_to_train_pairs_path=None, custom_prepare_train_batch_path=None, custom_loss_function_path=None, - custom_train_input_function_path=None, + custom_train_input_postprocess_path=None, ref_mode=None, diffusion_kl_beta=0.0, teacher_load="teacher", @@ -89,7 +89,7 @@ def test_dmd2_fills_only_unset_hook_paths(custom_loss): custom_expand_samples_to_train_pairs_path=None, custom_prepare_train_batch_path=None, custom_loss_function_path=custom_loss, - custom_train_input_function_path=None, + custom_train_input_postprocess_path=None, ref_mode=None, diffusion_kl_beta=0.0, teacher_load="teacher", @@ -105,7 +105,7 @@ def test_dmd2_fills_only_unset_hook_paths(custom_loss): assert args.custom_loss_function_path == ( custom_loss or "miles.backends.fsdp_utils.loss_hub.dmd2.dmd2_loss_formula" ) - assert args.custom_train_input_function_path.endswith("loss_hub.dmd2.select_scored_pairs") + assert args.custom_train_input_postprocess_path.endswith("loss_hub.dmd2.select_scored_pairs") assert args.ref_mode == "none" diff --git a/tests/fast/utils/test_trainer_config.py b/tests/fast/utils/test_trainer_config.py index e8b8de87e..4da8e85a3 100644 --- a/tests/fast/utils/test_trainer_config.py +++ b/tests/fast/utils/test_trainer_config.py @@ -47,7 +47,7 @@ def test_dmd2_critic_trains_first_from_its_own_checkpoint(load, save, critic_dir dmd2_critic_steps_per_rollout=5, custom_prepare_train_batch_path="my.prepare_generator", custom_loss_function_path="my.generator_loss", - custom_train_input_function_path="my.select_pairs", + custom_train_input_postprocess_path="my.select_pairs", custom_train_output_function_path=None, ) original = vars(args).copy() @@ -61,7 +61,7 @@ def test_dmd2_critic_trains_first_from_its_own_checkpoint(load, save, critic_dir assert (critic.num_steps_per_rollout, critic.global_batch_size) == (5, 8) 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_function_path is None + assert critic.custom_train_input_postprocess_path is None assert critic.custom_train_output_function_path.endswith("loss_hub.dmd2.score_last_step_samples") assert vars(actor) == {**original, "teacher_load": None} assert vars(args) == original From 55a681ed2a33899fa37f8511c1dac99bc8cc8e29 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Mon, 26 Oct 2026 06:28:02 +0000 Subject: [PATCH 10/33] perf(ray): sleep each trainer group right after its train --- tests/fast/test_train_diffusion.py | 24 ++++++++++++++++------ train_diffusion.py | 33 ++++++++++++------------------ 2 files changed, 31 insertions(+), 26 deletions(-) diff --git a/tests/fast/test_train_diffusion.py b/tests/fast/test_train_diffusion.py index ab6ab3a6b..8f5659811 100644 --- a/tests/fast/test_train_diffusion.py +++ b/tests/fast/test_train_diffusion.py @@ -1,5 +1,8 @@ """train_diffusion.py trains every trainer group on each rollout in declared order, handing each the earlier -outputs, then releases the rollout.""" +outputs, then releases the rollout. + +With --offload-train a group saves and sleeps right after its train, before the next group wakes. +""" from tests.ci.ci_register import register_cpu_ci @@ -7,6 +10,8 @@ from argparse import Namespace +import pytest + import train_diffusion @@ -44,6 +49,9 @@ def save_model(self, rollout_id, force_sync=False): def offload(self): self._events.append(("offload", self._role)) + def clear_memory(self): + self._events.append(("clear_memory", self._role)) + def update_weights(self): self._events.append(("update_weights", self._role)) @@ -59,8 +67,9 @@ def get(ref): return get -def test_every_trainer_group_trains_each_rollout_in_order(monkeypatch): - roles = ["critic", "actor"] +@pytest.mark.parametrize("roles", [["actor"], ["critic", "actor"]]) +@pytest.mark.parametrize("offload_train", [True, False]) +def test_every_trainer_group_trains_each_rollout_in_order(monkeypatch, roles, offload_train): events = [] monkeypatch.setattr(train_diffusion, "configure_logger", lambda: None) monkeypatch.setattr(train_diffusion, "init_tracking", lambda args: None) @@ -78,7 +87,7 @@ def test_every_trainer_group_trains_each_rollout_in_order(monkeypatch): start_rollout_id=0, num_rollout=2, offload_rollout=False, - offload_train=True, + offload_train=offload_train, eval_interval=None, save_interval=1, rollout_global_dataset=False, @@ -93,9 +102,12 @@ def test_every_trainer_group_trains_each_rollout_in_order(monkeypatch): expected += [ ("train_start", role, rollout_id, ("rollout_data", rollout_id), received), ("train_done", role, rollout_id), + ("save_model", role, rollout_id), ] + if offload_train: + expected += [("offload", role)] expected += [("release", rollout_id)] - expected += [("save_model", role, rollout_id) for role in roles] - expected += [("offload", role) for role in roles] + if not offload_train: + expected += [("clear_memory", role) for role in roles] expected += [("update_weights", "actor")] assert events == expected diff --git a/train_diffusion.py b/train_diffusion.py index d62b760fd..9aea22dae 100644 --- a/train_diffusion.py +++ b/train_diffusion.py @@ -40,22 +40,6 @@ def train(args): if args.num_rollout == 0 and args.eval_interval is not None: ray.get(rollout_manager.eval.remote(rollout_id=0)) - def offload_train(): - for train_group in train_groups.values(): - if args.offload_train: - train_group.offload() - else: - train_group.clear_memory() - - def save(rollout_id): - for train_group in train_groups.values(): - train_group.save_model( - rollout_id, - force_sync=rollout_id == args.num_rollout - 1, - ) - if args.rollout_global_dataset: - ray.get(rollout_manager.save.remote(rollout_id)) - # train loop. # note that for async training, one can change the position of the sync operation(ray.get). for rollout_id in range(args.start_rollout_id, args.num_rollout): @@ -70,6 +54,9 @@ def save(rollout_id): if args.offload_rollout: ray.get(rollout_manager.offload.remote()) + should_save = should_run_periodic_action( + rollout_id, args.save_interval, num_rollout_per_epoch, args.num_rollout + ) train_outputs = {} for role, train_group in train_groups.items(): logger.info(f"train: rollout {rollout_id} {role} train start") @@ -77,12 +64,18 @@ def save(rollout_id): # and hands them to the later groups, as RolloutManager.generate does for the shards. train_outputs[role] = ray.get(train_group.async_train(rollout_id, rollout_data_ref, train_outputs)) logger.info(f"train: rollout {rollout_id} {role} train done") + if should_save: + train_group.save_model(rollout_id, force_sync=rollout_id == args.num_rollout - 1) + # Its outputs already sit in the object store, so a group sleeps before the next one wakes. + if args.offload_train: + train_group.offload() ray.get(rollout_manager.release.remote(rollout_id)) - if should_run_periodic_action(rollout_id, args.save_interval, num_rollout_per_epoch, args.num_rollout): - save(rollout_id) - - offload_train() + if should_save and args.rollout_global_dataset: + ray.get(rollout_manager.save.remote(rollout_id)) + if not args.offload_train: + for train_group in train_groups.values(): + train_group.clear_memory() if args.offload_rollout: ray.get(rollout_manager.onload_weights.remote()) actor_model.update_weights() From c5644b670904e08606deacb6a7ed1686c1fc4619 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Mon, 26 Oct 2026 06:59:33 +0000 Subject: [PATCH 11/33] feat(dmd2): add the MiniMax H3 4-step DMD2 recipe with the media and metrics to judge it --- docs/models/h3/h3.md | 34 +++ docs/user-guide/cli-reference.md | 5 +- docs/user-guide/recipe-verification.md | 1 + docs/user-guide/rewards.md | 2 +- miles/backends/fsdp_utils/actor.py | 7 + miles/backends/fsdp_utils/loss_hub/dmd2.py | 16 +- miles/backends/fsdp_utils/metrics.py | 23 +- miles/ray/rollout.py | 107 +++++-- miles/rollout/rm_hub/__init__.py | 6 +- miles/rollout/sglang_diffusion_rollout.py | 5 +- miles/utils/arguments.py | 14 +- miles/utils/diffusion_rollout_response.py | 2 + miles/utils/types.py | 3 + ..._diffusion_dmd2_h3_t2va_16gpu_multinode.py | 279 ++++++++++++++++++ .../backends/fsdp_utils/test_loss_hub_dmd2.py | 27 +- .../fsdp_utils/test_train_input_hook.py | 1 + tests/fast/rollout/test_eval_media.py | 69 +++++ .../rollout/test_release_eval_sample_media.py | 26 +- tests/fast/rollout/test_rm_none.py | 27 ++ .../utils/test_diffusion_rollout_response.py | 15 +- 20 files changed, 634 insertions(+), 35 deletions(-) create mode 100644 scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py create mode 100644 tests/fast/rollout/test_eval_media.py create mode 100644 tests/fast/rollout/test_rm_none.py diff --git a/docs/models/h3/h3.md b/docs/models/h3/h3.md index c8e2aa027..b0a3ca943 100644 --- a/docs/models/h3/h3.md +++ b/docs/models/h3/h3.md @@ -61,6 +61,40 @@ python3 scripts/run_diffusion_grpo_h3_t2va_2gpu.py \ --rollout-batch-size 4 --n-samples-per-prompt 16 --num-rollout 200 ``` +### 4.3 DMD2 4-step distillation (2 nodes x 8 GPUs) + +Recipe: `scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py` — FastVideo's FastH3 Preview v1 +Dense / Data-Free recipe on `--loss-type dmd2`: full-parameter student and critic, frozen +teacher, lr 2e-6, 4 student steps with an Euler rollout stopped at a random step, an x0-space +critic, and 5 critic steps of 64 samples per student step. Prompts are the pinned +`vidprom_filtered_extended.txt` list, split by the script into fixed files with pinned hashes. + +**Status:** [○ NV — Not verified](../../user-guide/recipe-verification.md#nv) + +```bash +# after the multi-node bring-up, on the head node +MILES_SCRIPT_EXTERNAL_RAY=1 python3 scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py + +# references on the same eval prompts and seeds: the teacher at 50 steps, FastH3 at 4 steps +MILES_SCRIPT_EXTERNAL_RAY=1 python3 scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py --reference teacher +MILES_SCRIPT_EXTERNAL_RAY=1 python3 scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py --reference fasth3 +``` + +What to watch: + +| Signal | Where | Reading | +|---|---|---| +| Student media | W&B `eval_media/`, `//eval_media/eval_/` | Rollout 0 is the base model at 4 steps; later evals render the same 26 prompts and seeds. Compare with the two reference runs' `eval_0/` (same file names, `index.jsonl` lists prompt and seed) | +| Training media | W&B `rollout_media/`, every 10th rollout | Decoded x0 predictions from random stop steps, so their quality mixes steps | +| Critic | `train/critic-loss` | Rising to a plateau is the normal DMD2 shape; judge by the media | +| Distribution matching | `train/dmd2_grad_abs_mean`, `dmd2_score_gap_abs_mean` (critic vs teacher x0), `dmd2_teacher_dist_abs_mean` (student vs teacher x0, g's normalizer), each also `_step{i}` | A step whose curves drift away from the others is where the student breaks | +| Student output | `train/dmd2_x0_mean`, `train/dmd2_x0_std` | Latent statistics drifting from rollout 0 flag saturation | +| Rollout vs train | `train/x0_mean_abs_diff` (and `_step{i}`), `x0_rel_max` | The trainer's recomputed x0 against the rollout's; should stay small | +| Memory | `train/peak_memory_allocated_gb` (this process), `train/device_memory_used_gb` (whole GPU), both with a `critic-` twin | Headroom on each group's steps | + +The engine returns audio only with an sglang-miles change that adds it to the rollout response; +until then the saved videos are silent. Only the video stream is distilled, so listen for drift. + ## 5. Recipe notes SFT: the encode pool (`miles/rollout/encoder_hub/h3/`) imports the engine's own recipes diff --git a/docs/user-guide/cli-reference.md b/docs/user-guide/cli-reference.md index 8e616c814..89e043d22 100644 --- a/docs/user-guide/cli-reference.md +++ b/docs/user-guide/cli-reference.md @@ -182,7 +182,7 @@ See [Dtype Control](../advanced/dtype-control.md). | `--diffusion-num-steps` | int | `10` | | | `--diffusion-flow-shift` | float | – | Generation-schedule shift, sent to the engine. | | `--rollout-microgroup-size` | int | `1` | | -| `--diffusion-fps` | float | – | Video only. | +| `--diffusion-fps` | float | – | Video only. Also the fps logged and saved media play at (8 when unset); H3 drops it from the request, so set it to 24 there. | | `--diffusion-output-num-frames` | int | `1` | | | `--rollout-video-dtype` | enum | `keep` | `keep` / `uint8`: dtype of the decoded video in rollout responses. `uint8` quantizes engine-side by truncation (×255, then clamp), cutting the response ~4x. That matches the PickScore reward path; HPS, OCR and the OpenAI-API reward round instead, so keep `keep` for them and for any consumer that needs the float tensor. | | `--diffusion-guidance-scale` | float | `4.0` | | @@ -295,7 +295,7 @@ See [Dtype Control](../advanced/dtype-control.md). | Flag | Type | Default | Notes | |---|---|---|---| -| `--rm-type` | str | – | `pickscore` / `hps` / `hpsv3` / `ocr` / `openai_api` / `custom_api`. Overridable per sample via `metadata.rm_type`. Ignored when `--custom-rm-path` is set. | +| `--rm-type` | str | – | `pickscore` / `hps` / `hpsv3` / `ocr` / `openai_api` / `custom_api`, or `none` (constant 0, for a loss that reads no reward such as `dmd2`). Overridable per sample via `metadata.rm_type`. Ignored when `--custom-rm-path` is set. | | `--custom-api-rm-config` | str | – | Required for `--rm-type custom_api`: a YAML file or inline `base64:` with `actor_class`, `actor_kwargs`, `max_concurrency`. A flat mapping configures the default OpenAI-compatible image actor. | | `--openai-api-rm-config` | str | – | Required for `--rm-type openai_api`; same format as `--custom-api-rm-config`. | | `--group-rm` | flag | off | Score a whole prompt group at once. | @@ -407,6 +407,7 @@ Every one takes a dotted path. | `--train-only` | flag | off | No engines, no weight sync, no eval. (`--debug-train-only` is a legacy alias.) | | `--debug-skip-optimizer-step` | flag | off | No backward/step — weights never drift. Use it to measure pure forward divergence from the engine. | | `--save-debug-rollout-data` | path template | – | Fills `{rollout_id}`. | +| `--save-eval-media-dir` | path | – | Keeps every eval sample's video (with its audio when the engine returns it) or image under `/eval_/`, with an `index.jsonl` of prompts, seeds and rewards. Independent of `--wandb-log-num-images`. | | `--load-debug-rollout-data` | path template | – | Replays a rollout with **no engines started**. | | `--load-debug-rollout-data-subsample` | float | – | | | `--save-debug-train-data` | path template | – | Fills `{rollout_id}` and `{rank}`. | diff --git a/docs/user-guide/recipe-verification.md b/docs/user-guide/recipe-verification.md index 8ccd12878..8093a7c4e 100644 --- a/docs/user-guide/recipe-verification.md +++ b/docs/user-guide/recipe-verification.md @@ -61,3 +61,4 @@ count as verification. Flow-GRPO + PickScore. - `run_diffusion_sft_wan22.py` — Wan2.2 4-GPU LoRA SFT. - `run_diffusion_sft_h3_ref2va.py` — MiniMax H3 8-GPU Ref2VA LoRA SFT. + - `run_diffusion_dmd2_h3_t2va_16gpu_multinode.py` — MiniMax H3 16-GPU t2va 4-step DMD2. diff --git a/docs/user-guide/rewards.md b/docs/user-guide/rewards.md index 9c96a9e5d..ba1fcc586 100644 --- a/docs/user-guide/rewards.md +++ b/docs/user-guide/rewards.md @@ -13,7 +13,7 @@ For `--custom-rm-path`, `--custom-reward-post-process-path`, and other | Stage | Flag | Role | |---|---|---| -| Reward type | `--rm-type` | Selects built-in scorer (`pickscore`, `hps`, `hpsv3`, `ocr`, `openai_api`, `custom_api`); ignored when `--custom-rm-path` is set | +| Reward type | `--rm-type` | Selects built-in scorer (`pickscore`, `hps`, `hpsv3`, `ocr`, `openai_api`, `custom_api`), or `none` for a constant 0 when the loss reads no reward (DMD2); ignored when `--custom-rm-path` is set | | API reward config | `--openai-api-rm-config`, `--custom-api-rm-config` | YAML file or inline `base64:` for the two API rewards | | Per-sample override | `metadata.rm_type` in JSONL | Overrides global `--rm-type` | | Custom reward / norm | see [Customization](customization.md) | `--custom-rm-path`, `--custom-reward-post-process-path` | diff --git a/miles/backends/fsdp_utils/actor.py b/miles/backends/fsdp_utils/actor.py index 6fb4916b5..6ff8e8bba 100644 --- a/miles/backends/fsdp_utils/actor.py +++ b/miles/backends/fsdp_utils/actor.py @@ -461,6 +461,7 @@ def _train_core(self, rollout_id: int, rollout_data, external_data: dict[str, An device, self.models, sigma_buckets=self.args.log_loss_sigma_bucket, + num_rollout_steps=self.args.diffusion_num_steps, ) for pair_lo, pair_hi in microbatch_ranges: @@ -490,6 +491,12 @@ def _train_core(self, rollout_id: int, rollout_data, external_data: dict[str, An self.scaler.step(self.optimizer) self.scaler.update() self.lr_scheduler.step() + # Peak since the last reset, so a rollout's first step also covers scoring and wake-up before it. + metrics.emit_max("peak_memory_allocated_gb", torch.cuda.max_memory_allocated() / 2**30) + # Device-wide, so it also counts the other processes on this GPU (sleeping groups, the engine). + free_bytes, total_bytes = torch.cuda.mem_get_info() + metrics.emit_max("device_memory_used_gb", (total_bytes - free_bytes) / 2**30) + torch.cuda.reset_peak_memory_stats() else: self.optimizer.zero_grad(set_to_none=True) self.global_step += 1 diff --git a/miles/backends/fsdp_utils/loss_hub/dmd2.py b/miles/backends/fsdp_utils/loss_hub/dmd2.py index 2746b5f48..2e3a56900 100644 --- a/miles/backends/fsdp_utils/loss_hub/dmd2.py +++ b/miles/backends/fsdp_utils/loss_hub/dmd2.py @@ -10,7 +10,7 @@ from miles.backends.fsdp_utils.input_dtype_policy import apply_input_dtype_policy 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.backends.fsdp_utils.metrics import record_rollout_train_abs_diff +from miles.backends.fsdp_utils.metrics import record_rollout_train_abs_diff, step_metric_key from miles.utils.metric_buffer import MetricBuffer @@ -230,7 +230,19 @@ def dmd2_loss_formula( with torch.no_grad(): bsz = len(batch) metrics.emit_mean("loss", total=loss_sum, count=bsz) - metrics.emit_mean("dmd2_grad_abs_mean", total=grad.abs().mean(dim=reduce_dims).sum(), count=bsz) rollout_x0 = torch.stack([pair["x0"] for pair in batch]).to(device=x0.device, dtype=torch.float32) record_rollout_train_abs_diff(metrics, "x0", x0, rollout_x0) + per_pair = { + "dmd2_grad_abs_mean": grad.abs().mean(dim=reduce_dims), + "dmd2_score_gap_abs_mean": (x0_fake - x0_real).abs().mean(dim=reduce_dims), + "dmd2_teacher_dist_abs_mean": (x0 - x0_real).abs().mean(dim=reduce_dims), + "x0_mean_abs_diff": (x0 - rollout_x0).abs().mean(dim=reduce_dims), + } + for key in ("dmd2_grad_abs_mean", "dmd2_score_gap_abs_mean", "dmd2_teacher_dist_abs_mean"): + metrics.emit_mean(key, total=per_pair[key].sum(), count=bsz) + metrics.emit_mean("dmd2_x0_mean", total=x0.flatten(1).mean(dim=1).sum(), count=bsz) + metrics.emit_mean("dmd2_x0_std", total=x0.flatten(1).std(dim=1).sum(), count=bsz) + for index, pair in enumerate(batch): + for key, values in per_pair.items(): + metrics.emit_mean(step_metric_key(key, pair["step_index"]), total=values[index], count=1) return loss_sum diff --git a/miles/backends/fsdp_utils/metrics.py b/miles/backends/fsdp_utils/metrics.py index b51f17d89..093b48f3f 100644 --- a/miles/backends/fsdp_utils/metrics.py +++ b/miles/backends/fsdp_utils/metrics.py @@ -34,11 +34,29 @@ "nft_t_mean": MetricReduce.MEAN, "nft_num_timesteps": MetricReduce.MEAN, "dmd2_grad_abs_mean": MetricReduce.MEAN, + "dmd2_score_gap_abs_mean": MetricReduce.MEAN, + "dmd2_teacher_dist_abs_mean": MetricReduce.MEAN, + "dmd2_x0_mean": MetricReduce.MEAN, + "dmd2_x0_std": MetricReduce.MEAN, "x0_mean_abs_diff": MetricReduce.MEAN, "x0_max_abs_diff": MetricReduce.MAX, "x0_rel_max": MetricReduce.MAX, + "peak_memory_allocated_gb": MetricReduce.MAX, + "device_memory_used_gb": MetricReduce.MAX, } +# Also logged per rollout denoising step, under step_metric_key; a step no pair trained on is not logged. +STEP_SCHEMA = { + "dmd2_grad_abs_mean": MetricReduce.MEAN, + "dmd2_score_gap_abs_mean": MetricReduce.MEAN, + "dmd2_teacher_dist_abs_mean": MetricReduce.MEAN, + "x0_mean_abs_diff": MetricReduce.MEAN, +} + + +def step_metric_key(key: str, step_index: int) -> str: + return f"{key}_step{step_index}" + def sigma_bucket_key(stream_name: str, bucket: int, num_buckets: int) -> str: # Keep integer edges as floats (0.0, 1.0) so key names stay stable across bucket counts. @@ -50,10 +68,13 @@ def edge(value: float) -> str: def new_metric_buffer( - group, device: torch.device, components: Collection[str], sigma_buckets: int = 0 + group, device: torch.device, components: Collection[str], sigma_buckets: int = 0, num_rollout_steps: int = 0 ) -> MetricBuffer: """Buffer for one optimizer step, reducing over the DP group.""" schema = dict(SCHEMA) + for key, reduce in STEP_SCHEMA.items(): + for step_index in range(num_rollout_steps): + schema[step_metric_key(key, step_index)] = reduce # SFT loss by sigma bucket: velocity-MSE magnitude varies strongly with the # corruption level, so only bucketed curves are comparable across steps. for stream_name in ("visual", "audio"): diff --git a/miles/ray/rollout.py b/miles/ray/rollout.py index fe9b5c0af..2407e509d 100644 --- a/miles/ray/rollout.py +++ b/miles/ray/rollout.py @@ -122,6 +122,7 @@ def __init__(self, args, pg): self.nodes_per_engine = max(1, args.rollout_num_gpus_per_engine // args.num_gpus_per_node) self.rollout_engine_lock = Lock.options(num_cpus=1, num_gpus=0).remote() self.rollout_id = -1 + self._media_threads: list[threading.Thread] = [] self._metric_checker = MetricChecker.maybe_create(args) self._health_monitor = None if self.args.use_fault_tolerance: @@ -154,6 +155,9 @@ def _try_ci_fault_injection(self): def dispose(self): from miles.dashboard import hooks + # A media thread still encoding or uploading would lose the last eval's files. + for thread in self._media_threads: + thread.join() hooks.detach_and_flush() if self._metric_checker is not None: self._metric_checker.dispose() @@ -247,7 +251,8 @@ def eval(self, rollout_id): self._save_debug_rollout_data(data, rollout_id=rollout_id, evaluation=True) metrics = _log_eval_rollout_data(rollout_id, self.args, data, result.metrics) max_images = self.args.wandb_log_num_images - if max_images > 0: + save_dir = self.args.save_eval_media_dir + if max_images > 0 or save_dir is not None: self._log_images_async( { f"eval_media/{name}_images": payload["samples"] @@ -258,6 +263,7 @@ def eval(self, rollout_id): step_key="eval/step", step_value=compute_rollout_step(self.args, rollout_id), reward_key=self.args.eval_reward_key, + save_dir=None if save_dir is None else f"{save_dir}/eval_{rollout_id}", ) if self._metric_checker is not None: self._metric_checker.on_eval(metrics) @@ -460,7 +466,9 @@ def _convert_samples_to_train_data(self, samples: list[Sample] | list[list[Sampl def _log_images_async(self, *args, **kwargs) -> None: # mp4 encode + wandb upload take ~1min per log round; keep them off the train barrier - threading.Thread(target=self._log_images, args=args, kwargs=kwargs, daemon=True).start() + thread = threading.Thread(target=self._log_images, args=args, kwargs=kwargs, daemon=True) + thread.start() + self._media_threads.append(thread) def _log_images( self, @@ -470,6 +478,7 @@ def _log_images( step_key: str, step_value: int, reward_key: str | None, + save_dir: str | None = None, ) -> None: """Log per-key sample image grids under their own media namespace. @@ -478,39 +487,45 @@ def _log_images( media panels do not honor ``step_metric`` (they slide on the internal commit step), so panels pile up over a run — keeping them in their own namespace at least groups them in one UI section. + + With ``save_dir``, every sample's file is kept there, next to an ``index.jsonl`` of captions. """ + import json import os import tempfile - import imageio import wandb + fps = self.args.diffusion_fps or 8 with tempfile.TemporaryDirectory() as tmpdir: + media_dir = save_dir or tmpdir + os.makedirs(media_dir, exist_ok=True) log_dict: dict = {} + index_rows = [] for media_key, samples in media_key_to_samples.items(): media = [] - for sample_index, s in enumerate(samples[:max_images]): + for sample_index, s in enumerate(samples if save_dir else samples[:max_images]): t = s.generated_output if t is None or t.ndim != 4: continue - # generated_output is [C, F, H, W]; rescale to uint8 once. - arr = t.float().cpu().numpy() - if arr.max() <= 1.0 + 1e-3: - arr = arr * 255.0 - arr = np.clip(arr, 0, 255).astype(np.uint8) reward = s.reward if not reward_key else (s.reward or {}).get(reward_key) caption = f"{str(s.prompt)[:160]} | reward={reward}" - num_frames = arr.shape[1] - if num_frames > 1: - frames = [arr[:, f, :, :].transpose(1, 2, 0) for f in range(num_frames)] - path = os.path.join(tmpdir, f"{media_key.replace('/', '_')}_{sample_index}.mp4") - imageio.mimsave(path, frames, fps=8, codec="libx264", format="FFMPEG") - media.append(wandb.Video(path, caption=caption, format="mp4", fps=8)) + stem = os.path.join(media_dir, f"{media_key.replace('/', '_')}_{sample_index}") + path = write_sample_media(s, stem, fps=fps) + index_rows.append( + {"file": os.path.basename(path), "prompt": s.prompt, "seed": s.seed, "reward": reward} + ) + if sample_index >= max_images: + continue + if path.endswith(".mp4"): + media.append(wandb.Video(path, caption=caption, format="mp4", fps=fps)) else: - frame = arr[:, 0, :, :].transpose(1, 2, 0) - media.append(wandb.Image(frame, caption=caption)) + media.append(wandb.Image(path, caption=caption)) if media: log_dict[media_key] = media + if save_dir is not None: + with open(os.path.join(save_dir, "index.jsonl"), "w") as f: + f.writelines(json.dumps(row) + "\n" for row in index_rows) if not log_dict: return log_dict[step_key] = step_value @@ -520,6 +535,64 @@ def set_train_parallel_config(self, config: dict): self.train_parallel_config = config +def write_sample_media(sample: Sample, stem: str, *, fps: float) -> str: + """Write ``sample.generated_output`` as ``stem.mp4`` (with its audio track, if any) or ``stem.png``.""" + import imageio + + # generated_output is [C, F, H, W]; rescale to uint8 once. + arr = sample.generated_output.float().cpu().numpy() + if arr.max() <= 1.0 + 1e-3: + arr = arr * 255.0 + arr = np.clip(arr, 0, 255).astype(np.uint8) + if arr.shape[1] == 1: + path = f"{stem}.png" + imageio.imwrite(path, arr[:, 0, :, :].transpose(1, 2, 0)) + return path + path = f"{stem}.mp4" + frames = [arr[:, f, :, :].transpose(1, 2, 0) for f in range(arr.shape[1])] + video_path = path if sample.generated_audio is None else f"{stem}.video.mp4" + imageio.mimsave(video_path, frames, fps=fps, codec="libx264", format="FFMPEG") + if sample.generated_audio is not None: + _mux_audio(video_path, sample.generated_audio, sample.audio_sample_rate, path) + Path(video_path).unlink() + return path + + +def _mux_audio(video_path: str, audio: torch.Tensor, sample_rate: int, path: str) -> None: + import subprocess + + import imageio_ffmpeg + + # [C, L] waveform as interleaved float32 PCM on stdin. + pcm = audio.float().clamp(-1, 1).t().contiguous().numpy().tobytes() + subprocess.run( + [ + imageio_ffmpeg.get_ffmpeg_exe(), + "-y", + "-loglevel", + "error", + "-i", + video_path, + "-f", + "f32le", + "-ar", + str(sample_rate), + "-ac", + str(audio.shape[0]), + "-i", + "pipe:0", + "-c:v", + "copy", + "-c:a", + "aac", + "-shortest", + path, + ], + input=pcm, + check=True, + ) + + def init_rollout_engines(args, pg, all_rollout_engines): if args.train_only: return 0 diff --git a/miles/rollout/rm_hub/__init__.py b/miles/rollout/rm_hub/__init__.py index b526dff44..a52ef7f54 100644 --- a/miles/rollout/rm_hub/__init__.py +++ b/miles/rollout/rm_hub/__init__.py @@ -12,7 +12,9 @@ def _resolve_rm_type(args, sample: Sample) -> str: async def async_rm(args, sample: Sample, **kwargs): rm_type = _resolve_rm_type(args, sample) - if rm_type == "ocr": + if rm_type == "none": + return 0.0 + elif rm_type == "ocr": from .ocr import ocr_rm return (await ocr_rm(args, [sample]))[0] @@ -69,6 +71,8 @@ async def batched_async_rm( if samples: rm_types = [_resolve_rm_type(args, sample) for sample in samples] + if all(rm_type == "none" for rm_type in rm_types): + return [0.0] * len(samples) if all(rm_type == "pickscore" for rm_type in rm_types): from .pickscore import pickscore_rm diff --git a/miles/rollout/sglang_diffusion_rollout.py b/miles/rollout/sglang_diffusion_rollout.py index 6b23cf662..8da8471f4 100644 --- a/miles/rollout/sglang_diffusion_rollout.py +++ b/miles/rollout/sglang_diffusion_rollout.py @@ -415,12 +415,13 @@ async def generate_rollout_async( def release_eval_sample_media(args: Namespace, sample: Sample) -> None: - """Drop a scored eval sample's media, which only image logging and debug dumps still read.""" - if args.save_debug_rollout_data is not None: + """Drop a scored eval sample's media, which only image logging, saved eval media and debug dumps still read.""" + if args.save_debug_rollout_data is not None or args.save_eval_media_dir is not None: return if sample.index < args.wandb_log_num_images: return sample.generated_output = None + sample.generated_audio = None # eval only diff --git a/miles/utils/arguments.py b/miles/utils/arguments.py index a8a79afa8..6a53e36da 100644 --- a/miles/utils/arguments.py +++ b/miles/utils/arguments.py @@ -318,7 +318,8 @@ def add_rollout_arguments(parser): "--diffusion-fps", type=float, default=None, - help="Video fps for rollout; None for image models.", + help="Video fps for rollout, also the fps logged and saved media play at (8 when unset); " + "None for image models.", ) parser.add_argument( "--diffusion-output-num-frames", @@ -1375,6 +1376,13 @@ def add_debug_arguments(parser): "The file will be saved to `save_debug_rollout_data.format(rollout_id)`." ), ) + parser.add_argument( + "--save-eval-media-dir", + type=str, + default=None, + help="Keep every eval sample's video (with its audio, if the engine returns it) or image under " + "/eval_/, next to an index.jsonl of prompts, seeds and rewards.", + ) parser.add_argument( "--load-debug-rollout-data", type=str, @@ -1455,8 +1463,8 @@ def add_reward_model_arguments(parser): "--rm-type", type=str, default=None, - help="Built-in reward (pickscore / hps / hpsv3 / ocr / openai_api), or custom_api for a configurable actor. " - "Ignored when --custom-rm-path is set.", + help="Built-in reward (pickscore / hps / hpsv3 / ocr / openai_api), custom_api for a configurable actor, " + "or none for a constant 0 when the loss reads no reward. Ignored when --custom-rm-path is set.", ) for rm_type in ("custom_api", "openai_api"): parser.add_argument( diff --git a/miles/utils/diffusion_rollout_response.py b/miles/utils/diffusion_rollout_response.py index 0ef09d353..1d2cd3fa1 100644 --- a/miles/utils/diffusion_rollout_response.py +++ b/miles/utils/diffusion_rollout_response.py @@ -224,6 +224,8 @@ def apply_rollout_image_response( deserialize_func = _store_deserialize_func(sample.rollout_store_ref, deserialize_func) sample.generated_output = _normalize_generated_output(deserialize_func(body.get("generated_output"))) + sample.generated_audio = deserialize_func(body.get("generated_audio")) + sample.audio_sample_rate = body.get("audio_sample_rate") # Eval-mode rollout (rollout=False) sends no log_probs; train-mode always does. sample.rollout_log_probs = deserialize_func(body.get("rollout_log_probs")) sample.rollout_debug_tensors = _parse_rollout_debug_tensors( diff --git a/miles/utils/types.py b/miles/utils/types.py index bfce07c05..8b84fb645 100644 --- a/miles/utils/types.py +++ b/miles/utils/types.py @@ -83,6 +83,9 @@ class Sample: seed: int | None = None # Eager tensor on CPU. Image rollout shape: ``[C, T, H, W]`` (``T==1`` typical). generated_output: torch.Tensor | None = None + # [C, L] waveform at audio_sample_rate, for engines that also return audio (e.g. H3 t2va). + generated_audio: torch.Tensor | None = None + audio_sample_rate: int | None = None rollout_log_probs: torch.Tensor | None = None rollout_debug_tensors: RolloutDebugTensors | None = None denoising_env: DenoisingEnv | None = None diff --git a/scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py b/scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py new file mode 100644 index 000000000..664775df7 --- /dev/null +++ b/scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py @@ -0,0 +1,279 @@ +"""MiniMax H3 t2va 4-step DMD2 distillation, 2 nodes x 8 GPU, data-free (prompts only). + +Multi-node: this script submits into an EXISTING ray cluster of 2 x 8 colocated train/rollout GPUs -- +see docs/user-guide/launch-script.md (Multi-node training) for the bring-up, then run it on the head +node with MILES_SCRIPT_EXTERNAL_RAY=1. + +Recipe: FastVideo's FastH3 Preview v1 Dense / Data-Free (checkpoint_metadata.json of +FastVideo/FastVideo-FastH3-4-step-Preview-v1-Dense-DataFree, released at step 1000), mapped onto +--loss-type dmd2: + * full-parameter student and critic, both from MiniMax-H3, frozen MiniMax-H3 teacher; fp32 master, + bf16 forward; AdamW (0.9, 0.999), weight decay 0.01, constant lr 2e-6 for both, grad clip 1.0; + * 4 student steps on the uniform shift-12 grid (FastH3's rungs 999/749/500/250 within 1.4e-4 in + sigma), backward simulation by stopping each rollout at a random step, plain Euler (ode) rollout; + * teacher unguided (H3 has no CFG; FastH3 real_score_guidance_scale 1.0), critic loss in x0 space; + * scoring and critic sigma: unshifted range 0.001-0.999 read through shift 5. FastH3 sets + score_timestep_shift 2.4 on its own clock, documented as FastGen's shift 5 (12 / 5 = 2.4); + * one rollout = 5 critic steps of 64 samples + 1 student step on the last 64 (FastH3's + generator_update_interval 5 at global batch 64), so 1000 FastH3 steps = 200 rollouts. +Deviations: 768p 16:9 only (FastH3 mixes shapes); only the video stream is distilled (the rollout +records no audio trajectory), so audio follows whatever the shared layers learn -- listen to the media. + +Prompts: the 248,221 VidProM prompts of vidprom_filtered_extended.txt (the list Self-Forcing, NVlabs/rcm +and FastVideo's Wan data-free DMD train on), downloaded at a pinned revision and split here +deterministically: train 247,219 / test 1,000 / eval_media 26 (16 test prompts + 10 FastGen-DMD +demo prompts that also describe sound). The output hashes are pinned, so every node builds the same files. + +What to watch: eval media at rollout 0 is the base model at 4 steps; every --eval-interval rollouts +the student renders the same prompts and seeds. Videos (with audio once the engine returns it) go to +W&B eval_media/ and to //eval_media/eval_/. References on the same prompts +and seeds, for side-by-side comparison: + MILES_SCRIPT_EXTERNAL_RAY=1 python3 scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py --reference teacher + MILES_SCRIPT_EXTERNAL_RAY=1 python3 scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py --reference fasth3 +teacher = MiniMax-H3 at its default 50 steps; fasth3 = the FastH3 Dense / Data-Free student at 4 steps. + +Usage (after the multi-node bring-up, on the head node): + MILES_SCRIPT_EXTERNAL_RAY=1 python3 scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py +""" + +import hashlib +import json +import random +from dataclasses import dataclass +from pathlib import Path + +import typer + +import miles.utils.external_utils.command_utils as U + +MODEL = "MiniMaxAI/MiniMax-H3" +FASTH3_MODEL = "FastVideo/FastVideo-FastH3-4-step-Preview-v1-Dense-DataFree" +WANDB_PROJECT = "miles-diffusion-dmd2" + +PROMPT_REPO = "gdhe17/Self-Forcing" +PROMPT_FILE = "vidprom_filtered_extended.txt" +PROMPT_REVISION = "2f8b779212da279d212c22a509b66ad6552f350e" +PROMPT_SHA256 = "7896742f468bc8aef9e4547424d1ce0a951acdb2a82233790155401a99bf5aa5" +PROMPT_SPLIT_SEED = 1234 +NUM_TEST_PROMPTS = 1000 +NUM_EVAL_TEST_PROMPTS = 16 +# FastGen-DMD scripts/inference/prompts/flux3_t2va_demo.txt: short prompts that also describe sound. +DEMO_PROMPTS = [ + "a small red boat bobbing on gentle ocean waves at sunset, seagulls calling in the distance", + "a golden retriever running through autumn leaves in a park, leaves crunching underfoot", + "close-up of rain falling on a city street at night, neon reflections, soft rain sounds", + "a steam locomotive pulling into a rural station, whistle blowing, steam hissing", + "a campfire crackling on a beach under a starry sky, waves breaking softly", + "a busy street market in Marrakech, vendors calling out, colorful fabrics swaying", + "time-lapse of clouds rolling over snowy mountain peaks, wind howling", + "a jazz drummer playing a fast solo in a smoky club, cymbals shimmering", + "children playing soccer on a sunny field, laughter and a whistle", + "a waterfall cascading into a jungle pool, birds singing, water roaring", +] +SPLIT_SHA256 = { + "train.jsonl": "ec9ecd057ec5d3aa4b383224bc9071edfb73cf4a77b6594a5c9708068c39bc71", + "test.jsonl": "be22ea8ecdbe6d909099cd943fcd20cb4e5b0870160212b3483ad085e9f0684c", + "eval_media.jsonl": "9a9faf270a94fe98adbe28dfcb059a6acbc6d5f3d5f8da7a3e9a51c57e18fe60", +} + + +@dataclass +class ScriptArgs(U.ExecuteTrainConfig): + num_rollout: int = 200 + # 5 critic steps x 64 samples; the student steps on the last 64. + rollout_batch_size: int = 320 + eval_interval: int = 5 + save_interval: int = 50 + duration_seconds: float = 5.0 + data_dir: str = "/root/datasets" + # "teacher" or "fasth3": render the eval prompts with that model instead of training. + reference: str = "" + extra_args: str = "" + + +def _sha256(path: Path) -> str: + h = hashlib.sha256() + with open(path, "rb") as f: + for chunk in iter(lambda: f.read(1 << 20), b""): + h.update(chunk) + return h.hexdigest() + + +def _write_jsonl(path: Path, prompts: list[str]) -> None: + with open(path, "w", encoding="utf-8") as f: + for prompt in prompts: + f.write(json.dumps({"input": prompt}, ensure_ascii=False) + "\n") + + +def prepare(args: ScriptArgs) -> str: + """Download the pinned prompt list and split it; returns the directory of the jsonl files.""" + from huggingface_hub import hf_hub_download + + root = Path(args.data_dir) / "vidprom-extended" + prompt_dir = root / "prompts" + if all((prompt_dir / name).exists() and _sha256(prompt_dir / name) == h for name, h in SPLIT_SHA256.items()): + return str(prompt_dir) + + raw = Path(hf_hub_download(PROMPT_REPO, PROMPT_FILE, revision=PROMPT_REVISION, local_dir=root / "raw")) + if _sha256(raw) != PROMPT_SHA256: + raise RuntimeError(f"{raw} does not match the pinned sha256 {PROMPT_SHA256}") + prompts = list(dict.fromkeys(line.strip() for line in raw.read_text(encoding="utf-8").splitlines())) + prompts = [prompt for prompt in prompts if prompt] + order = list(range(len(prompts))) + random.Random(PROMPT_SPLIT_SEED).shuffle(order) + shuffled = [prompts[i] for i in order] + test = shuffled[:NUM_TEST_PROMPTS] + splits = { + "train.jsonl": shuffled[NUM_TEST_PROMPTS:], + "test.jsonl": test, + "eval_media.jsonl": test[:NUM_EVAL_TEST_PROMPTS] + DEMO_PROMPTS, + } + prompt_dir.mkdir(parents=True, exist_ok=True) + for name, split in splits.items(): + _write_jsonl(prompt_dir / name, split) + if _sha256(prompt_dir / name) != SPLIT_SHA256[name]: + raise RuntimeError(f"{prompt_dir / name} does not match the pinned split sha256") + return str(prompt_dir) + + +def _fasth3_checkpoint(data_dir: str) -> str: + """MiniMax-H3 with FastH3's transformer: the export shares every other component and both shifts.""" + from huggingface_hub import snapshot_download + + base = Path(snapshot_download(MODEL)) + student = Path(snapshot_download(FASTH3_MODEL, allow_patterns=["transformer/*"])) + overlay = Path(data_dir) / "MiniMax-H3-FastH3-4step-dense" + overlay.mkdir(parents=True, exist_ok=True) + for entry in base.iterdir(): + link = overlay / entry.name + if not link.is_symlink(): + link.symlink_to(student / "transformer" if entry.name == "transformer" else entry) + return str(overlay) + + +def execute(args: ScriptArgs, prompt_dir: str) -> None: + run_name = f"diffusion_dmd2_h3_t2va_{args.reference or 'student'}_{U.create_run_id()}" + run_dir = f"{args.output_dir}/{run_name}" + + rollout_args = ( + "--rollout-function-path miles.rollout.sglang_diffusion_rollout.generate_rollout " + f"--prompt-data {prompt_dir}/train.jsonl " + "--input-key input " + f"--rollout-batch-size {args.rollout_batch_size} " + "--n-samples-per-prompt 1 " + "--num-steps-per-rollout 1 " + "--rollout-microgroup-size 1 " + "--rm-type none " + "--rollout-video-dtype uint8 " + ) + + diffusion_args = ( + "--diffusion-task t2va " + "--diffusion-num-steps 4 " + "--diffusion-guidance-scale 1.0 " + "--diffusion-h3-aspect-ratio 16:9 " + f"--diffusion-h3-duration-seconds {args.duration_seconds} " + "--diffusion-flow-shift 12.0 " + "--diffusion-audio-flow-shift 3.0 " + # H3 drops fps from the request; this sets the playback rate of the logged and saved media. + "--diffusion-fps 24 " + ) + + eval_args = ( + f"--eval-prompt-data dmd2_media {prompt_dir}/eval_media.jsonl " + "--n-samples-per-eval-prompt 1 " + f"--save-eval-media-dir {run_dir}/eval_media " + ) + + # Every eval video; training rollouts (x0 predictions from random stop steps) only every 10th rollout. + wandb_args = U.get_default_wandb_args( + __file__, + run_id=run_name, + project=WANDB_PROJECT, + wandb_log_num_images=NUM_EVAL_TEST_PROMPTS + len(DEMO_PROMPTS), + wandb_log_image_interval=10, + ) + + sglang_args = ( + "--use-miles-router " + "--sglang-server-concurrency 2 " + "--sglang-tp-size 2 " + "--sglang-sp-degree 1 " + "--sglang-ulysses-degree 1 " + "--sglang-ring-degree 1 " + "--sglang-dit-precision bf16 " + "--update-weight-buffer-size 4294967296 " + ) + + topology_args = ( + "--actor-num-nodes 2 " + "--actor-num-gpus-per-node 8 " + "--num-gpus-per-node 8 " + "--rollout-num-gpus 16 " + "--rollout-num-gpus-per-engine 2 " + "--rollout-parser-num-workers 16 " + "--colocate " + # H3 denoising blocks the engine's event loop for tens of seconds per sample. + "--rollout-health-check-interval 60 " + "--miles-router-health-check-failure-threshold 30 " + ) + + if args.reference: + if args.reference == "teacher": + checkpoint, eval_steps = MODEL, 50 + elif args.reference == "fasth3": + checkpoint, eval_steps = _fasth3_checkpoint(args.data_dir), 4 + else: + raise ValueError(f"--reference must be teacher or fasth3, got {args.reference!r}") + mode_args = ( + f"--hf-checkpoint {checkpoint} " + "--debug-rollout-only " + "--num-rollout 0 " + "--eval-interval 1 " + f"--diffusion-eval-num-steps {eval_steps} " + ) + else: + mode_args = ( + f"--hf-checkpoint {MODEL} " + f"--save {run_dir}/ckpt " + f"--save-interval {args.save_interval} " + f"--num-rollout {args.num_rollout} " + f"--eval-interval {args.eval_interval} " + "--loss-type dmd2 " + f"--teacher-load {MODEL} " + "--dmd2-teacher-guidance-scale 1.0 " + "--dmd2-critic-steps-per-rollout 5 " + "--dmd2-score-sigma-range 0.001 0.999 " + "--dmd2-critic-loss-space x0 " + "--fsdp-flow-shift visual=5.0 " + "--diffusion-step-strategy-path miles.rollout.step_strategy_hub.stop_at_random_step " + "--diffusion-sde-type ode " + "--lr 2e-6 " + "--critic-lr 2e-6 " + "--weight-decay 0.01 " + "--train-backend fsdp " + "--fsdp-master-dtype fp32 " + "--fsdp-reduce-dtype fp32 " + "--diffusion-forward-dtype bf16 " + "--gradient-checkpointing " + ) + + U.execute_train( + train_args=( + f"{mode_args} {rollout_args} {diffusion_args} {eval_args} {wandb_args} {sglang_args} " + f"{topology_args} {args.extra_args}" + ), + num_gpus_per_node=8, + config=args, + extra_env_vars={"PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True"}, + ) + + +@U.dataclass_cli +def main(args: ScriptArgs) -> None: + prompt_dir = prepare(args) + execute(args, prompt_dir) + + +if __name__ == "__main__": + typer.run(main) diff --git a/tests/fast/backends/fsdp_utils/test_loss_hub_dmd2.py b/tests/fast/backends/fsdp_utils/test_loss_hub_dmd2.py index 6aed8b941..eca56850e 100644 --- a/tests/fast/backends/fsdp_utils/test_loss_hub_dmd2.py +++ b/tests/fast/backends/fsdp_utils/test_loss_hub_dmd2.py @@ -41,6 +41,7 @@ test_surrogate_gradient_matches_the_reference same gradient as the reference's batch-mean MSE test_critic_matching_the_teacher_gives_no_gradient x0_fake == x0_real ──► zero loss and gradient test_gaussian_student_moves_toward_the_teacher analytic scores: sign and normalization move mu + test_health_metrics_are_recorded_overall_and_per_step score gap, teacher distance, x0 stats, split by stop step """ from tests.ci.ci_register import register_cpu_ci @@ -358,13 +359,14 @@ def _generator_pairs(num_pairs): "sigma": 0.75 - 0.25 * n, "denoising_env": DenoisingEnv(pos_cond_kwargs=_cond(1.0 + n), neg_cond_kwargs=None), "sample_index": 100 + n, + "step_index": n, } for n in range(num_pairs) ] def _metrics(): - return new_metric_buffer(None, torch.device("cpu"), ["transformer"]) + return new_metric_buffer(None, torch.device("cpu"), ["transformer"], num_rollout_steps=4) def _loss(ctx, pairs, x0): @@ -485,3 +487,26 @@ def test_trainer_and_rollout_x0_diff_is_recorded(): reduced = metrics.reduce() assert reduced["x0_mean_abs_diff"] == pytest.approx(0.25) assert reduced["x0_max_abs_diff"] == pytest.approx(0.25) + + +def test_health_metrics_are_recorded_overall_and_per_step(): + ctx = _ctx() + pairs = _generator_pairs(2) + # Pair n stopped at step n: x0 = 0.5 + n against a teacher x0 of 0 and a critic x0 of 0.25. + x0 = torch.stack([pair["x0"] for pair in pairs]) + torch.tensor([0.5, 1.5]).view(2, 1, 1, 1) + ctx.external_data = {"critic": _scores(pairs, torch.zeros(2, *LATENT_SHAPE), torch.full((2, *LATENT_SHAPE), 0.25))} + + _, metrics = _loss(ctx, pairs, x0) + + reduced = metrics.reduce() + assert reduced["dmd2_score_gap_abs_mean"] == pytest.approx(0.25) + assert reduced["dmd2_teacher_dist_abs_mean"] == pytest.approx(1.0) + assert reduced["dmd2_x0_mean"] == pytest.approx(1.0) + assert reduced["dmd2_x0_std"] == pytest.approx(0.0, abs=1e-6) + for step, distance in enumerate([0.5, 1.5]): + assert reduced[f"dmd2_teacher_dist_abs_mean_step{step}"] == pytest.approx(distance) + assert reduced[f"dmd2_grad_abs_mean_step{step}"] == pytest.approx(0.25 / distance) + assert reduced[f"dmd2_score_gap_abs_mean_step{step}"] == pytest.approx(0.25) + assert reduced[f"x0_mean_abs_diff_step{step}"] == pytest.approx(distance) + # No pair stopped at steps 2 or 3, so they log nothing. + assert not any(key.endswith(("_step2", "_step3")) for key in reduced) 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 b6525ac0d..52b85f9b5 100644 --- a/tests/fast/backends/fsdp_utils/test_train_input_hook.py +++ b/tests/fast/backends/fsdp_utils/test_train_input_hook.py @@ -65,6 +65,7 @@ def _actor(train_input, train_output, forwarded): diffusion_recompute_old_log_prob=False, debug_skip_optimizer_step=True, log_loss_sigma_bucket=0, + diffusion_num_steps=4, ), _forward_dtype=torch.float32, parallel_state=SimpleNamespace(dp_rank=0, dp_group=None), diff --git a/tests/fast/rollout/test_eval_media.py b/tests/fast/rollout/test_eval_media.py new file mode 100644 index 000000000..a3dfb68f5 --- /dev/null +++ b/tests/fast/rollout/test_eval_media.py @@ -0,0 +1,69 @@ +"""Logged and saved media: videos play at --diffusion-fps and carry the engine's audio; eval media can be kept on disk.""" + +from tests.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=20, suite="stage-a-cpu", labels=[]) + +import json +import subprocess +from argparse import Namespace +from types import SimpleNamespace + +import imageio_ffmpeg +import pytest +import torch + +from miles.ray import rollout +from miles.utils.types import Sample + + +def _streams(path): + probe = subprocess.run([imageio_ffmpeg.get_ffmpeg_exe(), "-i", path], capture_output=True, text=True) + return {kind for kind in ("Video", "Audio") if f": {kind}:" in probe.stderr} + + +def _video_sample(**fields): + return Sample(prompt="a boat", seed=7, generated_output=torch.rand(3, 12, 16, 16), **fields) + + +def test_video_plays_at_the_given_fps(tmp_path): + path = rollout.write_sample_media(_video_sample(), str(tmp_path / "clip"), fps=24) + + frames, seconds = imageio_ffmpeg.count_frames_and_secs(path) + assert path.endswith(".mp4") and frames == 12 + assert seconds == pytest.approx(0.5, abs=0.05) + assert _streams(path) == {"Video"} + + +def test_audio_is_muxed_into_the_video(tmp_path): + sample = _video_sample(generated_audio=torch.rand(2, 24000) * 2 - 1, audio_sample_rate=48000) + + path = rollout.write_sample_media(sample, str(tmp_path / "clip"), fps=24) + + assert _streams(path) == {"Video", "Audio"} + assert sorted(p.name for p in tmp_path.iterdir()) == ["clip.mp4"] + + +def test_a_single_frame_is_saved_as_an_image(tmp_path): + sample = Sample(generated_output=torch.rand(3, 1, 16, 16)) + + assert rollout.write_sample_media(sample, str(tmp_path / "image"), fps=8).endswith(".png") + + +def test_saved_eval_media_keeps_every_sample_without_wandb(tmp_path): + manager = SimpleNamespace(args=Namespace(diffusion_fps=24)) + samples = [_video_sample(), Sample(prompt="no media")] + + rollout.RolloutManager.__ray_metadata__.modified_class._log_images( + manager, + {"eval_media/demo_images": samples}, + max_images=0, + step_key="eval/step", + step_value=0, + reward_key=None, + save_dir=str(tmp_path), + ) + + assert sorted(p.name for p in tmp_path.iterdir()) == ["eval_media_demo_images_0.mp4", "index.jsonl"] + rows = [json.loads(line) for line in (tmp_path / "index.jsonl").read_text().splitlines()] + assert rows == [{"file": "eval_media_demo_images_0.mp4", "prompt": "a boat", "seed": 7, "reward": None}] diff --git a/tests/fast/rollout/test_release_eval_sample_media.py b/tests/fast/rollout/test_release_eval_sample_media.py index 174ebf708..9bba64990 100644 --- a/tests/fast/rollout/test_release_eval_sample_media.py +++ b/tests/fast/rollout/test_release_eval_sample_media.py @@ -11,21 +11,30 @@ def make_sample(index: int) -> Sample: - return Sample(index=index, generated_output=torch.zeros(3, 1, 4, 4)) + return Sample(index=index, generated_output=torch.zeros(3, 1, 4, 4), generated_audio=torch.zeros(2, 8)) + + +def make_args(save_debug_rollout_data=None, wandb_log_num_images=2, save_eval_media_dir=None) -> Namespace: + return Namespace( + save_debug_rollout_data=save_debug_rollout_data, + wandb_log_num_images=wandb_log_num_images, + save_eval_media_dir=save_eval_media_dir, + ) def test_media_released_when_not_logged(): sample = make_sample(index=3) - release_eval_sample_media(Namespace(save_debug_rollout_data=None, wandb_log_num_images=2), sample) + release_eval_sample_media(make_args(), sample) assert sample.generated_output is None + assert sample.generated_audio is None def test_media_kept_for_logged_samples(): sample = make_sample(index=1) - release_eval_sample_media(Namespace(save_debug_rollout_data=None, wandb_log_num_images=2), sample) + release_eval_sample_media(make_args(), sample) assert sample.generated_output is not None @@ -33,6 +42,15 @@ def test_media_kept_for_logged_samples(): def test_media_kept_when_debug_dump_enabled(): sample = make_sample(index=3) - release_eval_sample_media(Namespace(save_debug_rollout_data="/tmp/dump", wandb_log_num_images=0), sample) + release_eval_sample_media(make_args(save_debug_rollout_data="/tmp/dump", wandb_log_num_images=0), sample) + + assert sample.generated_output is not None + + +def test_media_kept_when_eval_media_is_saved(): + sample = make_sample(index=3) + + release_eval_sample_media(make_args(wandb_log_num_images=0, save_eval_media_dir="/tmp/media"), sample) assert sample.generated_output is not None + assert sample.generated_audio is not None diff --git a/tests/fast/rollout/test_rm_none.py b/tests/fast/rollout/test_rm_none.py new file mode 100644 index 000000000..9ab131873 --- /dev/null +++ b/tests/fast/rollout/test_rm_none.py @@ -0,0 +1,27 @@ +"""--rm-type none: a constant 0 reward for losses that read none, with no scorer behind it.""" + +from tests.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=5, suite="stage-a-cpu", labels=[]) + +import asyncio +from argparse import Namespace + +from miles.rollout.rm_hub import async_rm, batched_async_rm +from miles.utils.types import Sample + + +def _args(rm_type): + return Namespace(rm_type=rm_type, custom_rm_path=None) + + +def test_none_rewards_every_sample_with_zero(): + samples = [Sample(index=index) for index in range(3)] + + assert asyncio.run(batched_async_rm(_args("none"), samples)) == [0.0, 0.0, 0.0] + + +def test_per_sample_none_overrides_the_global_reward(): + sample = Sample(index=0, metadata={"rm_type": "none"}) + + assert asyncio.run(async_rm(_args("pickscore"), sample)) == 0.0 diff --git a/tests/fast/utils/test_diffusion_rollout_response.py b/tests/fast/utils/test_diffusion_rollout_response.py index 4a67185cb..ad211d4da 100644 --- a/tests/fast/utils/test_diffusion_rollout_response.py +++ b/tests/fast/utils/test_diffusion_rollout_response.py @@ -5,7 +5,8 @@ import pytest import torch -from miles.utils.diffusion_rollout_response import _normalize_generated_output +from miles.utils.diffusion_rollout_response import _normalize_generated_output, apply_rollout_image_response +from miles.utils.types import Sample @pytest.mark.parametrize( @@ -103,3 +104,15 @@ def _tensor_bytes(tensor: torch.Tensor) -> bytes: from safetensors.torch import save return save({"t": tensor}) + + +def test_response_audio_fills_the_sample(): + audio = torch.zeros(2, 480) + body = {"generated_audio": audio, "audio_sample_rate": 48000} + + sample = apply_rollout_image_response(Sample(), body, deserialize_func=lambda value: value) + + assert sample.generated_audio is audio + assert sample.audio_sample_rate == 48000 + silent = apply_rollout_image_response(Sample(), {}, deserialize_func=lambda value: value) + assert silent.generated_audio is None and silent.audio_sample_rate is None From 7542deb87c307013db6de574f07f79565ce71fde Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Mon, 26 Oct 2026 07:36:43 +0000 Subject: [PATCH 12/33] feat(dmd2): skip the engine's VAE decode of training rollouts when no reward reads the media --- docs/models/h3/h3.md | 7 ++- docs/user-guide/cli-reference.md | 4 +- docs/user-guide/rewards.md | 2 +- miles/rollout/sglang_diffusion_rollout.py | 5 +- miles/utils/arguments.py | 5 +- ..._diffusion_dmd2_h3_t2va_16gpu_multinode.py | 3 +- .../rollout/test_rollout_negative_prompt.py | 2 + .../rollout/test_rollout_payload_media.py | 55 +++++++++++++++++++ 8 files changed, 72 insertions(+), 11 deletions(-) create mode 100644 tests/fast/rollout/test_rollout_payload_media.py diff --git a/docs/models/h3/h3.md b/docs/models/h3/h3.md index b0a3ca943..663df4819 100644 --- a/docs/models/h3/h3.md +++ b/docs/models/h3/h3.md @@ -85,15 +85,16 @@ What to watch: | Signal | Where | Reading | |---|---|---| | Student media | W&B `eval_media/`, `//eval_media/eval_/` | Rollout 0 is the base model at 4 steps; later evals render the same 26 prompts and seeds. Compare with the two reference runs' `eval_0/` (same file names, `index.jsonl` lists prompt and seed) | -| Training media | W&B `rollout_media/`, every 10th rollout | Decoded x0 predictions from random stop steps, so their quality mixes steps | | Critic | `train/critic-loss` | Rising to a plateau is the normal DMD2 shape; judge by the media | | Distribution matching | `train/dmd2_grad_abs_mean`, `dmd2_score_gap_abs_mean` (critic vs teacher x0), `dmd2_teacher_dist_abs_mean` (student vs teacher x0, g's normalizer), each also `_step{i}` | A step whose curves drift away from the others is where the student breaks | | Student output | `train/dmd2_x0_mean`, `train/dmd2_x0_std` | Latent statistics drifting from rollout 0 flag saturation | | Rollout vs train | `train/x0_mean_abs_diff` (and `_step{i}`), `x0_rel_max` | The trainer's recomputed x0 against the rollout's; should stay small | | Memory | `train/peak_memory_allocated_gb` (this process), `train/device_memory_used_gb` (whole GPU), both with a `critic-` twin | Headroom on each group's steps | -The engine returns audio only with an sglang-miles change that adds it to the rollout response; -until then the saved videos are silent. Only the video stream is distilled, so listen for drift. +Training rollouts carry no media: with `--rm-type none` the engine skips their VAE decode, so the +student is judged on the eval renders. The engine returns audio only with an sglang-miles change that +adds it to the rollout response; until then the saved videos are silent. Only the video stream is +distilled, so listen for drift. ## 5. Recipe notes diff --git a/docs/user-guide/cli-reference.md b/docs/user-guide/cli-reference.md index 89e043d22..49987b3e9 100644 --- a/docs/user-guide/cli-reference.md +++ b/docs/user-guide/cli-reference.md @@ -184,7 +184,7 @@ See [Dtype Control](../advanced/dtype-control.md). | `--rollout-microgroup-size` | int | `1` | | | `--diffusion-fps` | float | – | Video only. Also the fps logged and saved media play at (8 when unset); H3 drops it from the request, so set it to 24 there. | | `--diffusion-output-num-frames` | int | `1` | | -| `--rollout-video-dtype` | enum | `keep` | `keep` / `uint8`: dtype of the decoded video in rollout responses. `uint8` quantizes engine-side by truncation (×255, then clamp), cutting the response ~4x. That matches the PickScore reward path; HPS, OCR and the OpenAI-API reward round instead, so keep `keep` for them and for any consumer that needs the float tensor. | +| `--rollout-video-dtype` | enum | `keep` | `keep` / `uint8`: dtype of the decoded video in rollout and eval responses. `uint8` quantizes engine-side by truncation (×255, then clamp), cutting the response ~4x. That matches the PickScore reward path; HPS, OCR and the OpenAI-API reward round instead, so keep `keep` for them and for any consumer that needs the float tensor. | | `--diffusion-guidance-scale` | float | `4.0` | | | `--diffusion-guidance-scale-2` | float | – | Wan2.2 low-noise expert; **required** when training it. | | `--diffusion-true-cfg-scale` | float | – | | @@ -295,7 +295,7 @@ See [Dtype Control](../advanced/dtype-control.md). | Flag | Type | Default | Notes | |---|---|---|---| -| `--rm-type` | str | – | `pickscore` / `hps` / `hpsv3` / `ocr` / `openai_api` / `custom_api`, or `none` (constant 0, for a loss that reads no reward such as `dmd2`). Overridable per sample via `metadata.rm_type`. Ignored when `--custom-rm-path` is set. | +| `--rm-type` | str | – | `pickscore` / `hps` / `hpsv3` / `ocr` / `openai_api` / `custom_api`, or `none` (constant 0, for a loss that reads no reward such as `dmd2`; training rollouts then skip the engine's VAE decode, which needs an engine with `rollout_return_generated_output`, while eval still decodes). Overridable per sample via `metadata.rm_type`. Ignored when `--custom-rm-path` is set. | | `--custom-api-rm-config` | str | – | Required for `--rm-type custom_api`: a YAML file or inline `base64:` with `actor_class`, `actor_kwargs`, `max_concurrency`. A flat mapping configures the default OpenAI-compatible image actor. | | `--openai-api-rm-config` | str | – | Required for `--rm-type openai_api`; same format as `--custom-api-rm-config`. | | `--group-rm` | flag | off | Score a whole prompt group at once. | diff --git a/docs/user-guide/rewards.md b/docs/user-guide/rewards.md index ba1fcc586..04a35f576 100644 --- a/docs/user-guide/rewards.md +++ b/docs/user-guide/rewards.md @@ -13,7 +13,7 @@ For `--custom-rm-path`, `--custom-reward-post-process-path`, and other | Stage | Flag | Role | |---|---|---| -| Reward type | `--rm-type` | Selects built-in scorer (`pickscore`, `hps`, `hpsv3`, `ocr`, `openai_api`, `custom_api`), or `none` for a constant 0 when the loss reads no reward (DMD2); ignored when `--custom-rm-path` is set | +| Reward type | `--rm-type` | Selects built-in scorer (`pickscore`, `hps`, `hpsv3`, `ocr`, `openai_api`, `custom_api`), or `none` for a constant 0 when the loss reads no reward (DMD2), which also skips decoding training rollouts; ignored when `--custom-rm-path` is set | | API reward config | `--openai-api-rm-config`, `--custom-api-rm-config` | YAML file or inline `base64:` for the two API rewards | | Per-sample override | `metadata.rm_type` in JSONL | Overrides global `--rm-type` | | Custom reward / norm | see [Customization](customization.md) | `--custom-rm-path`, `--custom-reward-post-process-path` | diff --git a/miles/rollout/sglang_diffusion_rollout.py b/miles/rollout/sglang_diffusion_rollout.py index 8da8471f4..41ddc0bca 100644 --- a/miles/rollout/sglang_diffusion_rollout.py +++ b/miles/rollout/sglang_diffusion_rollout.py @@ -46,6 +46,7 @@ def build_rollout_sampling_params( "num_inference_steps": num_steps, "guidance_scale": args.diffusion_guidance_scale, "true_cfg_scale": args.diffusion_true_cfg_scale, + "rollout_video_dtype": args.rollout_video_dtype, } if neg is not None: @@ -61,13 +62,15 @@ def build_rollout_sampling_params( "rollout_noise_level": args.diffusion_noise_level, "rollout_log_prob_no_const": args.diffusion_log_prob_no_const, "rollout_debug_mode": args.diffusion_debug_mode, - "rollout_video_dtype": args.rollout_video_dtype, "rollout_return_denoising_env": True, "rollout_return_dit_trajectory": True, } ) if args.use_output_store: sampling_params["rollout_return_outputs_via_store"] = True + if args.rm_type == "none" and args.custom_rm_path is None: + # No reward reads the decoded media, so the engine skips the VAE decode of training rollouts. + sampling_params["rollout_return_generated_output"] = False if args.diffusion_output_num_frames is not None: sampling_params["num_frames"] = int(args.diffusion_output_num_frames) diff --git a/miles/utils/arguments.py b/miles/utils/arguments.py index 6a53e36da..2d872019a 100644 --- a/miles/utils/arguments.py +++ b/miles/utils/arguments.py @@ -308,7 +308,7 @@ def add_rollout_arguments(parser): choices=["keep", "uint8"], default="keep", help=( - "Dtype of the decoded video in rollout responses. 'keep' returns the " + "Dtype of the decoded video in rollout and eval responses. 'keep' returns the " "engine's raw float tensor; 'uint8' quantises engine-side with the same " "formula the reward path applies, cutting the response body ~4x. Use " "'keep' for any consumer that needs the unquantised tensor." @@ -1464,7 +1464,8 @@ def add_reward_model_arguments(parser): type=str, default=None, help="Built-in reward (pickscore / hps / hpsv3 / ocr / openai_api), custom_api for a configurable actor, " - "or none for a constant 0 when the loss reads no reward. Ignored when --custom-rm-path is set.", + "or none for a constant 0 when the loss reads no reward; none also has the engine skip decoding " + "training rollouts, whose media nothing reads. Ignored when --custom-rm-path is set.", ) for rm_type in ("custom_api", "openai_api"): parser.add_argument( diff --git a/scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py b/scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py index 664775df7..01853a707 100644 --- a/scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py +++ b/scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py @@ -185,13 +185,12 @@ def execute(args: ScriptArgs, prompt_dir: str) -> None: f"--save-eval-media-dir {run_dir}/eval_media " ) - # Every eval video; training rollouts (x0 predictions from random stop steps) only every 10th rollout. + # Every eval video; training rollouts carry no media, since --rm-type none skips their decode. wandb_args = U.get_default_wandb_args( __file__, run_id=run_name, project=WANDB_PROJECT, wandb_log_num_images=NUM_EVAL_TEST_PROMPTS + len(DEMO_PROMPTS), - wandb_log_image_interval=10, ) sglang_args = ( diff --git a/tests/fast/rollout/test_rollout_negative_prompt.py b/tests/fast/rollout/test_rollout_negative_prompt.py index f7feb1aba..3d6f5436e 100644 --- a/tests/fast/rollout/test_rollout_negative_prompt.py +++ b/tests/fast/rollout/test_rollout_negative_prompt.py @@ -34,6 +34,8 @@ def _args(**overrides): rollout_video_dtype="keep", train_pipeline_config_path=None, use_output_store=False, + rm_type="pickscore", + custom_rm_path=None, ) values.update(overrides) return Namespace(**values) diff --git a/tests/fast/rollout/test_rollout_payload_media.py b/tests/fast/rollout/test_rollout_payload_media.py new file mode 100644 index 000000000..070a77c24 --- /dev/null +++ b/tests/fast/rollout/test_rollout_payload_media.py @@ -0,0 +1,55 @@ +"""Which media the engine decodes and ships: training rollouts skip the decode when no reward reads it.""" + +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.rollout.sglang_diffusion_rollout import build_rollout_sampling_params + + +def _args(**overrides): + values = dict( + diffusion_negative_prompt=None, + diffusion_generator_device=None, + diffusion_quality="exact", + diffusion_eval_num_steps=None, + diffusion_num_steps=4, + diffusion_width=832, + diffusion_height=480, + diffusion_guidance_scale=1.0, + diffusion_guidance_scale_2=None, + diffusion_true_cfg_scale=None, + diffusion_output_num_frames=None, + diffusion_fps=None, + diffusion_sde_type="ode", + diffusion_noise_level=0.7, + diffusion_log_prob_no_const=False, + diffusion_debug_mode=False, + rollout_video_dtype="uint8", + train_pipeline_config_path=None, + rm_type="none", + custom_rm_path=None, + use_output_store=False, + ) + values.update(overrides) + return Namespace(**values) + + +def test_training_rollouts_skip_the_decode_when_no_reward_reads_it(): + assert build_rollout_sampling_params(_args())["rollout_return_generated_output"] is False + # Eval renders are what gets looked at, so they always decode. + assert "rollout_return_generated_output" not in build_rollout_sampling_params(_args(), evaluation=True) + + +@pytest.mark.parametrize("overrides", [{"rm_type": "pickscore"}, {"custom_rm_path": "my.rm"}]) +def test_a_reward_keeps_the_decode(overrides): + assert "rollout_return_generated_output" not in build_rollout_sampling_params(_args(**overrides)) + + +def test_video_dtype_applies_to_eval_too(): + for evaluation in (False, True): + assert build_rollout_sampling_params(_args(), evaluation=evaluation)["rollout_video_dtype"] == "uint8" From 37695a101c318aef13a944c00cd9de94b2bd80cf Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Tue, 10 Nov 2026 12:45:51 +0000 Subject: [PATCH 13/33] build: declare imageio-ffmpeg, which the eval media muxing imports miles/ray/rollout.py imports imageio_ffmpeg to mux the eval audio; the GPU image had it only as a transitive dependency and the hosted CPU suite not at all, so tests/fast/rollout/test_eval_media.py failed to import there. Co-Authored-By: Claude Mythos 5.1 --- requirements.txt | 3 +++ 1 file changed, 3 insertions(+) diff --git a/requirements.txt b/requirements.txt index e94e2257f..56d20fe36 100644 --- a/requirements.txt +++ b/requirements.txt @@ -5,6 +5,9 @@ datasets==4.4.2 diffusers==0.41.0 fastapi==0.128.8 httpx[http2]==0.28.1 +# miles/ray/rollout.py muxes eval audio through imageio_ffmpeg's bundled ffmpeg; the GPU image only had it +# transitively (cosmos-guardrail, moviepy) and the hosted CPU suite not at all. +imageio-ffmpeg==0.5.1 ltx-core @ git+https://github.com/Lightricks/LTX-2.git@780984275fd47128b02bef9b5c085404276866ee#subdirectory=packages/ltx-core mcp[cli]==1.25.0 memray==1.19.1 From 8328ef8d8af9734edb2fd8e706d13aa391c8fdb3 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Wed, 11 Nov 2026 09:31:30 +0000 Subject: [PATCH 14/33] docs(h3): say the DMD2 recipe downloads the VidProM prompt list from the Hub --- docs/models/h3/h3.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/models/h3/h3.md b/docs/models/h3/h3.md index 663df4819..361e0ebf5 100644 --- a/docs/models/h3/h3.md +++ b/docs/models/h3/h3.md @@ -66,8 +66,9 @@ python3 scripts/run_diffusion_grpo_h3_t2va_2gpu.py \ Recipe: `scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py` — FastVideo's FastH3 Preview v1 Dense / Data-Free recipe on `--loss-type dmd2`: full-parameter student and critic, frozen teacher, lr 2e-6, 4 student steps with an Euler rollout stopped at a random step, an x0-space -critic, and 5 critic steps of 64 samples per student step. Prompts are the pinned -`vidprom_filtered_extended.txt` list, split by the script into fixed files with pinned hashes. +critic, and 5 critic steps of 64 samples per student step. Prompts are not in the repo: the +script downloads `vidprom_filtered_extended.txt` from the Hub (`gdhe17/Self-Forcing` at a pinned +revision and sha256) into `--data-dir` and splits it into fixed files with pinned hashes. **Status:** [○ NV — Not verified](../../user-guide/recipe-verification.md#nv) From 0d9f731bc1bea90ef21d259b7abe93ba36b3ae35 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Wed, 11 Nov 2026 09:37:53 +0000 Subject: [PATCH 15/33] docs(dmd2): count the VidProM prompts after dedup --- scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py b/scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py index 01853a707..5fce3b92e 100644 --- a/scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py +++ b/scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py @@ -19,7 +19,7 @@ Deviations: 768p 16:9 only (FastH3 mixes shapes); only the video stream is distilled (the rollout records no audio trajectory), so audio follows whatever the shared layers learn -- listen to the media. -Prompts: the 248,221 VidProM prompts of vidprom_filtered_extended.txt (the list Self-Forcing, NVlabs/rcm +Prompts: the 248,219 unique VidProM prompts (248,221 lines) of vidprom_filtered_extended.txt (the list Self-Forcing, NVlabs/rcm and FastVideo's Wan data-free DMD train on), downloaded at a pinned revision and split here deterministically: train 247,219 / test 1,000 / eval_media 26 (16 test prompts + 10 FastGen-DMD demo prompts that also describe sound). The output hashes are pinned, so every node builds the same files. From ce6bda59f73c279dff217bfe8ca198ba2b00a306 Mon Sep 17 00:00:00 2001 From: rockdu Date: Wed, 11 Nov 2026 04:53:28 -0800 Subject: [PATCH 16/33] fix(dmd2): load the FastH3 reference by its Hub id on every node --- ..._diffusion_dmd2_h3_t2va_16gpu_multinode.py | 19 +++---------------- 1 file changed, 3 insertions(+), 16 deletions(-) diff --git a/scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py b/scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py index 5fce3b92e..e13c3ed20 100644 --- a/scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py +++ b/scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py @@ -136,21 +136,6 @@ def prepare(args: ScriptArgs) -> str: return str(prompt_dir) -def _fasth3_checkpoint(data_dir: str) -> str: - """MiniMax-H3 with FastH3's transformer: the export shares every other component and both shifts.""" - from huggingface_hub import snapshot_download - - base = Path(snapshot_download(MODEL)) - student = Path(snapshot_download(FASTH3_MODEL, allow_patterns=["transformer/*"])) - overlay = Path(data_dir) / "MiniMax-H3-FastH3-4step-dense" - overlay.mkdir(parents=True, exist_ok=True) - for entry in base.iterdir(): - link = overlay / entry.name - if not link.is_symlink(): - link.symlink_to(student / "transformer" if entry.name == "transformer" else entry) - return str(overlay) - - def execute(args: ScriptArgs, prompt_dir: str) -> None: run_name = f"diffusion_dmd2_h3_t2va_{args.reference or 'student'}_{U.create_run_id()}" run_dir = f"{args.output_dir}/{run_name}" @@ -221,11 +206,13 @@ def execute(args: ScriptArgs, prompt_dir: str) -> None: if args.reference == "teacher": checkpoint, eval_steps = MODEL, 50 elif args.reference == "fasth3": - checkpoint, eval_steps = _fasth3_checkpoint(args.data_dir), 4 + checkpoint, eval_steps = FASTH3_MODEL, 4 else: raise ValueError(f"--reference must be teacher or fasth3, got {args.reference!r}") mode_args = ( f"--hf-checkpoint {checkpoint} " + # Every engine fetches the checkpoint by its Hub id; the FastH3 name matches no H3 pattern. + "--diffusion-model-family h3 " "--debug-rollout-only " "--num-rollout 0 " "--eval-interval 1 " From 4ed4e789be5e4601825b5559914b3c385e4db516 Mon Sep 17 00:00:00 2001 From: rockdu Date: Tue, 10 Nov 2026 13:09:23 -0800 Subject: [PATCH 17/33] refactor(args): drop the teacher consumer check Whether a hook forwards the teacher is the hook's business; the argument layer cannot tell from --loss-type and the hook paths who will read it, so the check only ever guessed. --teacher-load is now accepted under every loss type (dmd2 still requires it). --- docs/fsdp_model_roles.md | 5 +- docs/user-guide/cli-reference.md | 2 +- miles/utils/arguments.py | 9 --- .../utils/test_loss_type_recipes_parse.py | 64 +++++++++++++++++++ tests/fast/utils/test_reference_arguments.py | 8 +-- 5 files changed, 68 insertions(+), 20 deletions(-) create mode 100644 tests/fast/utils/test_loss_type_recipes_parse.py 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 49987b3e9..3fd207726 100644 --- a/docs/user-guide/cli-reference.md +++ b/docs/user-guide/cli-reference.md @@ -273,7 +273,7 @@ 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. | diff --git a/miles/utils/arguments.py b/miles/utils/arguments.py index 2d872019a..f2e2fae9a 100644 --- a/miles/utils/arguments.py +++ b/miles/utils/arguments.py @@ -1885,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") 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..11d72166c --- /dev/null +++ b/tests/fast/utils/test_loss_type_recipes_parse.py @@ -0,0 +1,64 @@ +"""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 + +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.utils.arguments import get_miles_extra_args_provider, miles_validate_args, set_default_diffusion_args + +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", +} + + +@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 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): From b745e50fb5a129a2f25a738ad14c8ac6dc83829b Mon Sep 17 00:00:00 2001 From: rockdu Date: Tue, 10 Nov 2026 13:09:23 -0800 Subject: [PATCH 18/33] refactor(fsdp): select loss hooks from a (loss_type, role) table Stop filling the --custom-*-path arguments on behalf of nft / dmd2 and stop overriding them per trainer role: a group's prepare, formula, train-input and train-output hooks come from loss_hub.LOSS_HOOKS keyed by (loss_type, role), the way miles core's get_loss_function does. Only custom_loss reads the path flags. The critic overrides shrink to the six values that really differ (checkpoint, lr, load/save dirs, steps, batch). --- docs/advanced/sde-backend.md | 2 +- docs/developer/contributor-guide.md | 2 +- docs/user-guide/customization.md | 56 +++++---- miles/backends/fsdp_utils/actor.py | 49 ++------ .../backends/fsdp_utils/loss_hub/__init__.py | 71 +++++++++-- miles/utils/arguments.py | 36 ++---- miles/utils/trainer_config.py | 4 - scripts/run_diffusion_sft_h3_ref2va.py | 2 - scripts/run_diffusion_sft_h3_t2va.py | 2 - scripts/run_diffusion_sft_wan22.py | 2 - .../backends/fsdp_utils/test_loss_hub_nft.py | 2 - .../fsdp_utils/test_loss_hub_selection.py | 116 ++++++++++++++++++ .../fsdp_utils/test_reference_models.py | 3 +- .../fsdp_utils/test_train_input_hook.py | 3 +- tests/fast/utils/test_dmd2_arguments.py | 31 ++--- .../utils/test_loss_type_recipes_parse.py | 36 ++++++ tests/fast/utils/test_sft_encoder_args.py | 21 ++-- .../utils/test_sglang_parallel_defaults.py | 2 - .../fast/utils/test_train_sde_backend_args.py | 13 +- tests/fast/utils/test_trainer_config.py | 22 ++-- 20 files changed, 316 insertions(+), 159 deletions(-) create mode 100644 tests/fast/backends/fsdp_utils/test_loss_hub_selection.py diff --git a/docs/advanced/sde-backend.md b/docs/advanced/sde-backend.md index a11138306..977e39cd7 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/user-guide/customization.md b/docs/user-guide/customization.md index cdc441dcf..8fae7a8ee 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,8 @@ 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 +Builds DiT inputs from train pairs; the loss hub's table above lists each loss type's. +`PreparedBatch.latents`, `timesteps` and `timesteps_for_model` are keyed by latent stream name: `"visual"`, plus e.g. `"audio"` for joint audio-video models. 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/utils/arguments.py b/miles/utils/arguments.py index f2e2fae9a..7fd49052b 100644 --- a/miles/utils/arguments.py +++ b/miles/utils/arguments.py @@ -1809,16 +1809,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: @@ -1829,12 +1824,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" @@ -1960,13 +1949,15 @@ 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_dmd2_args(args) -> None: @@ -2133,12 +2124,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 6d1636479..65af5fb4b 100644 --- a/miles/utils/trainer_config.py +++ b/miles/utils/trainer_config.py @@ -22,10 +22,6 @@ def compute_trainer_configs(args: Namespace) -> list[TrainerConfig]: "save": None if args.save is None else args.save.rstrip("/") + "_critic", "num_steps_per_rollout": critic_steps, "global_batch_size": args.global_batch_size // critic_steps, - "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 15fb5c0b1..4fe95f6d7 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 @@ -58,9 +58,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", @@ -78,8 +75,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, @@ -87,9 +83,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", @@ -97,16 +90,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_type_recipes_parse.py b/tests/fast/utils/test_loss_type_recipes_parse.py index 11d72166c..cddffcd14 100644 --- a/tests/fast/utils/test_loss_type_recipes_parse.py +++ b/tests/fast/utils/test_loss_type_recipes_parse.py @@ -2,6 +2,9 @@ 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. @@ -18,7 +21,9 @@ 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 " @@ -30,6 +35,18 @@ "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", } @@ -62,3 +79,22 @@ def run(argv: str) -> Namespace: 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} diff --git a/tests/fast/utils/test_sft_encoder_args.py b/tests/fast/utils/test_sft_encoder_args.py index a78170b1e..c3f64384a 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,7 @@ 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_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 4da8e85a3..e2a29c77b 100644 --- a/tests/fast/utils/test_trainer_config.py +++ b/tests/fast/utils/test_trainer_config.py @@ -45,10 +45,6 @@ def test_dmd2_critic_trains_first_from_its_own_checkpoint(load, save, critic_dir global_batch_size=40, num_steps_per_rollout=1, dmd2_critic_steps_per_rollout=5, - 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() @@ -56,12 +52,16 @@ 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.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 and how + # many steps it takes; 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, + } assert vars(actor) == {**original, "teacher_load": None} assert vars(args) == original From 972e01e6721319b8daefe671d4d275b4b70ca20c Mon Sep 17 00:00:00 2001 From: rockdu Date: Tue, 10 Nov 2026 13:09:23 -0800 Subject: [PATCH 19/33] fix(args): reject --custom-*-path outside --loss-type custom_loss A path given under any other loss type would be silently ignored now that the table selects the hooks, so fail at parse time instead. --- docs/user-guide/cli-reference.md | 10 +++--- docs/user-guide/customization.md | 14 +++++--- miles/rollout/sft_rollout.py | 2 +- miles/utils/arguments.py | 33 +++++++++++++---- tests/fast/utils/test_loss_hook_path_args.py | 35 +++++++++++++++++++ .../utils/test_loss_type_recipes_parse.py | 5 +++ tests/fast/utils/test_sft_encoder_args.py | 7 ++++ 7 files changed, 88 insertions(+), 18 deletions(-) create mode 100644 tests/fast/utils/test_loss_hook_path_args.py diff --git a/docs/user-guide/cli-reference.md b/docs/user-guide/cli-reference.md index 3fd207726..90464a587 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. | @@ -276,10 +276,10 @@ See [Dtype Control](../advanced/dtype-control.md). | `--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 8fae7a8ee..97e33f8a8 100644 --- a/docs/user-guide/customization.md +++ b/docs/user-guide/customization.md @@ -283,7 +283,8 @@ def prepare(ctx, batch, *, pad_to_len=None) -> PreparedBatch: ... ``` -Builds DiT inputs from train pairs; the loss hub's table above lists each loss type's. +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. @@ -295,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` @@ -305,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 @@ -318,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/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 7fd49052b..c1dfa5930 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( @@ -1960,6 +1962,22 @@ def validate_train_sde_backend(args) -> None: ) +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: if args.loss_type != "dmd2": if args.critic_load is not None or args.critic_lr is not None: @@ -2038,6 +2056,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) 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 index cddffcd14..cf8164ea8 100644 --- a/tests/fast/utils/test_loss_type_recipes_parse.py +++ b/tests/fast/utils/test_loss_type_recipes_parse.py @@ -98,3 +98,8 @@ def test_dmd2_trainer_groups_get_their_hooks_by_role(parse): "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_sft_encoder_args.py b/tests/fast/utils/test_sft_encoder_args.py index c3f64384a..ab2120336 100644 --- a/tests/fast/utils/test_sft_encoder_args.py +++ b/tests/fast/utils/test_sft_encoder_args.py @@ -108,6 +108,13 @@ def test_builtin_producer_still_requires_checkpoint(args: Namespace) -> None: miles_validate_args(args) +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"): From 711dc3ad8dcca12961d0d52cc99f225c49158b97 Mon Sep 17 00:00:00 2001 From: rockdu Date: Tue, 10 Nov 2026 13:09:42 -0800 Subject: [PATCH 20/33] fix(args): reject --diffusion-recompute-old-log-prob under dmd2 DMD2 has no log-prob ratio to recompute, and once the recompute loop passes its real step index the critic's last window would run its scoring prepare and formula a second time. sft_loss and nft already reject the flag. --- miles/utils/arguments.py | 2 ++ tests/fast/utils/test_dmd2_arguments.py | 4 +++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/miles/utils/arguments.py b/miles/utils/arguments.py index c1dfa5930..7690e4649 100644 --- a/miles/utils/arguments.py +++ b/miles/utils/arguments.py @@ -2005,6 +2005,8 @@ def validate_dmd2_args(args) -> None: ) if args.ref_mode != "none": raise ValueError("--loss-type dmd2 uses no reference model; drop --ref-mode and --diffusion-kl-beta") + if args.diffusion_recompute_old_log_prob: + raise ValueError("--diffusion-recompute-old-log-prob is only supported for policy_loss / Flow-GRPO, not DMD2") if args.num_steps_per_rollout != 1: raise ValueError( f"--loss-type dmd2 takes one actor step per rollout, got --num-steps-per-rollout " diff --git a/tests/fast/utils/test_dmd2_arguments.py b/tests/fast/utils/test_dmd2_arguments.py index 4fe95f6d7..c37525af4 100644 --- a/tests/fast/utils/test_dmd2_arguments.py +++ b/tests/fast/utils/test_dmd2_arguments.py @@ -7,7 +7,7 @@ takes --dmd2-critic-steps-per-rollout steps over each DP shard other losses ──► --critic-load / --critic-lr have no consumer and are rejected teacher score ──► CFG --dmd2-teacher-guidance-scale >= 1 - actor ──► unguided rollouts, one step per rollout + actor ──► unguided rollouts, one step per rollout, no old-log-prob recompute (no ratio) """ from tests.ci.ci_register import register_cpu_ci @@ -36,6 +36,7 @@ def _args(**overrides): diffusion_true_cfg_scale=None, use_lora=False, ref_mode="none", + diffusion_recompute_old_log_prob=False, num_steps_per_rollout=1, global_batch_size=40, actor_num_gpus_per_node=4, @@ -126,6 +127,7 @@ def test_valid_dmd2_args_pass_unchanged(): ({"use_lora": True}, "drop --use-lora"), ({"teacher_lora_adapter_paths": ["teacher-adapter"]}, "drop --use-lora and --teacher-lora-adapter-path"), ({"ref_mode": "ref"}, "uses no reference model"), + ({"diffusion_recompute_old_log_prob": True}, "not DMD2"), ({"num_steps_per_rollout": 2}, "one actor step per rollout"), ({"dmd2_critic_steps_per_rollout": 0}, "must be >= 1"), # 40 samples over 2 DP shards = 20 per shard, which 3 critic steps cannot split. From 0861d2dbc1979d3b084ca7ee83c5374b166e030e Mon Sep 17 00:00:00 2001 From: rockdu Date: Tue, 10 Nov 2026 13:09:42 -0800 Subject: [PATCH 21/33] refactor(fsdp): pass the loop counters to the hooks as arguments microbatch_id and optim_step_idx were written onto DiffusionLossContext before every forward and read back by the hooks; the planned micro-batch prefetch would race on them. They are now required keyword arguments of every prepare and formula hook, passed by the two trunk loops; the numbering is unchanged (training from 0, the old-log-prob recompute of windows 1.. reuses their training forwards' numbers). --- docs/user-guide/customization.md | 6 +- miles/backends/fsdp_utils/actor.py | 25 +++-- miles/backends/fsdp_utils/loss_hub/dmd2.py | 30 ++++- .../backends/fsdp_utils/loss_hub/flow_grpo.py | 9 +- miles/backends/fsdp_utils/loss_hub/nft.py | 8 +- miles/backends/fsdp_utils/loss_hub/sft.py | 16 ++- miles/backends/fsdp_utils/loss_hub/types.py | 2 - miles/utils/arguments.py | 2 +- .../fsdp_utils/_reference_models_worker.py | 18 ++- .../backends/fsdp_utils/test_h3_streams.py | 22 +++- .../backends/fsdp_utils/test_loss_hub_dmd2.py | 67 ++++++++---- .../backends/fsdp_utils/test_loss_hub_nft.py | 20 ++-- .../fsdp_utils/test_loss_hub_selection.py | 2 +- .../backends/fsdp_utils/test_loss_hub_sft.py | 103 ++++++++++++------ .../fsdp_utils/test_reference_models.py | 36 +++++- .../fsdp_utils/test_train_input_hook.py | 37 ++++++- 16 files changed, 293 insertions(+), 110 deletions(-) diff --git a/docs/user-guide/customization.md b/docs/user-guide/customization.md index 97e33f8a8..1c0900518 100644 --- a/docs/user-guide/customization.md +++ b/docs/user-guide/customization.md @@ -279,12 +279,14 @@ def convert_samples_to_train_data(args, samples) -> dict: ### `--custom-prepare-train-batch-path` ```python -def prepare(ctx, batch, *, pad_to_len=None) -> PreparedBatch: +def prepare(ctx, batch, *, microbatch_id, optim_step_idx, pad_to_len=None) -> PreparedBatch: ... ``` 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. +above. Builds DiT inputs from train pairs. `microbatch_id` numbers the micro-batch within the rollout (training +counts from 0; the old-log-prob recompute of windows 1.. passes their training forwards' numbers) and +`optim_step_idx` is its optimizer step; the built-in hooks seed their noise from `microbatch_id`. `PreparedBatch.latents`, `timesteps` and `timesteps_for_model` are keyed by latent stream name: `"visual"`, plus e.g. `"audio"` for joint audio-video models. diff --git a/miles/backends/fsdp_utils/actor.py b/miles/backends/fsdp_utils/actor.py index ac5b0cf1e..7d0cdf0cb 100644 --- a/miles/backends/fsdp_utils/actor.py +++ b/miles/backends/fsdp_utils/actor.py @@ -409,27 +409,27 @@ def _train_core(self, rollout_id: int, rollout_data, external_data: dict[str, An sigma_buckets=self.args.log_loss_sigma_bucket, ) # Skip window 0: its training forward runs on the same pre-update weights and doubles as the recompute. - # Start the id after window 0's micro-batches to stay aligned with the training loop. + # Each later window's micro-batches get the ids and step index of their training forwards. microbatch_id = len(microbatch_schedule[0]) - for microbatch_ranges in microbatch_schedule[1:]: + for optim_step_idx, microbatch_ranges in enumerate(microbatch_schedule[1:], 1): legacy_pad_to_len = self._maybe_legacy_window_pad_len(train_pairs, microbatch_ranges) for pair_lo, pair_hi in microbatch_ranges: - loss_ctx.microbatch_id = microbatch_id - microbatch_id += 1 self._forward_train_pair_batch( loss_ctx, train_pairs[pair_lo:pair_hi], + microbatch_id=microbatch_id, + optim_step_idx=optim_step_idx, metrics=unused_metrics, pad_to_len=legacy_pad_to_len, write_old_log_prob=True, ) + microbatch_id += 1 # ------------- Forward / Backward ------------- with timer("actor_train"): microbatch_id = 0 for optim_step_idx, microbatch_ranges in enumerate(microbatch_schedule): self.optimizer.zero_grad(set_to_none=True) - loss_ctx.optim_step_idx = optim_step_idx old_log_prob_from_new = self.args.diffusion_recompute_old_log_prob and optim_step_idx == 0 @@ -448,15 +448,16 @@ def _train_core(self, rollout_id: int, rollout_data, external_data: dict[str, An for pair_lo, pair_hi in microbatch_ranges: chunk = train_pairs[pair_lo:pair_hi] - loss_ctx.microbatch_id = microbatch_id - microbatch_id += 1 loss_sum = self._forward_train_pair_batch( loss_ctx, chunk, + microbatch_id=microbatch_id, + optim_step_idx=optim_step_idx, metrics=metrics, pad_to_len=legacy_pad_to_len, old_log_prob_from_new=old_log_prob_from_new, ) + microbatch_id += 1 if not self.args.debug_skip_optimizer_step: # ShardedGradScaler keeps fp16 policy grads from underflowing # (required for SD3.5 fp16 forward); no-op for bf16/fp32. @@ -509,13 +510,18 @@ def _forward_train_pair_batch( ctx: DiffusionLossContext, batch: list, *, + microbatch_id: int, + optim_step_idx: int, metrics: MetricBuffer, pad_to_len: int | None = None, write_old_log_prob: bool = False, old_log_prob_from_new: bool = False, ) -> torch.Tensor | None: - """Run one prepared diffusion micro-batch.""" - prepared = self.loss_hooks.prepare(ctx, batch, pad_to_len=pad_to_len) + """Run one prepared diffusion micro-batch: number ``microbatch_id`` of the rollout, in optimizer step + ``optim_step_idx``.""" + prepared = self.loss_hooks.prepare( + ctx, batch, microbatch_id=microbatch_id, optim_step_idx=optim_step_idx, pad_to_len=pad_to_len + ) train_pipeline_config = self.train_pipeline_config forward_dtype = self._forward_dtype @@ -574,6 +580,7 @@ def _compute_noise_pred(model) -> dict[str, torch.Tensor]: old_pred=old_pred, ref_pred=ref_pred, metrics=metrics, + optim_step_idx=optim_step_idx, write_old_log_prob=write_old_log_prob, old_log_prob_from_new=old_log_prob_from_new, ) diff --git a/miles/backends/fsdp_utils/loss_hub/dmd2.py b/miles/backends/fsdp_utils/loss_hub/dmd2.py index 2e3a56900..06257db27 100644 --- a/miles/backends/fsdp_utils/loss_hub/dmd2.py +++ b/miles/backends/fsdp_utils/loss_hub/dmd2.py @@ -18,6 +18,8 @@ def prepare_critic_batch( ctx: DiffusionLossContext, batch: list[dict], *, + microbatch_id: int, + optim_step_idx: int, pad_to_len: int | None = None, ) -> PreparedBatch: """SFT flow matching on the student's x0 predictions, conditioned on their rollout prompts. @@ -33,12 +35,19 @@ def prepare_critic_batch( for pair in batch ] grid_index_range = None - if _is_scoring_step(ctx): + if _is_scoring_step(ctx, optim_step_idx): min_sigma, max_sigma = ctx.args.dmd2_score_sigma_range num_train_timesteps = config.num_train_timesteps # Grid index i carries the unshifted sigma 1 - i / num_train_timesteps. grid_index_range = (round(num_train_timesteps * (1 - max_sigma)), round(num_train_timesteps * (1 - min_sigma))) - return prepare_sft_batch(ctx, sft_batch, pad_to_len=pad_to_len, grid_index_range=grid_index_range) + return prepare_sft_batch( + ctx, + sft_batch, + microbatch_id=microbatch_id, + optim_step_idx=optim_step_idx, + pad_to_len=pad_to_len, + grid_index_range=grid_index_range, + ) def critic_loss_formula( @@ -50,6 +59,7 @@ def critic_loss_formula( old_pred: dict[str, torch.Tensor] | None, ref_pred: dict[str, torch.Tensor] | None, metrics: MetricBuffer, + optim_step_idx: int, write_old_log_prob: bool = False, old_log_prob_from_new: bool = False, ) -> torch.Tensor: @@ -59,7 +69,7 @@ def critic_loss_formula( """ latents = prepared.latents["visual"] sigmas = prepared.extras["sigmas"]["visual"].view(len(batch), *([1] * (latents.ndim - 1))) - if _is_scoring_step(ctx): + if _is_scoring_step(ctx, optim_step_idx): x0_fake = latents - sigmas * new_pred["visual"].detach().float() ctx.train_output_inputs.append( (batch, prepared.component_name, latents, prepared.timesteps["visual"], sigmas, x0_fake) @@ -77,6 +87,7 @@ def critic_loss_formula( old_pred=old_pred, ref_pred=ref_pred, metrics=metrics, + optim_step_idx=optim_step_idx, write_old_log_prob=write_old_log_prob, old_log_prob_from_new=old_log_prob_from_new, ) @@ -97,8 +108,8 @@ def score_last_step_samples(ctx: DiffusionLossContext, train_pairs: list[dict]) return predictions -def _is_scoring_step(ctx: DiffusionLossContext) -> bool: - return ctx.optim_step_idx == ctx.args.num_steps_per_rollout - 1 +def _is_scoring_step(ctx: DiffusionLossContext, optim_step_idx: int) -> bool: + return optim_step_idx == ctx.args.num_steps_per_rollout - 1 def _predict_velocity( @@ -171,9 +182,15 @@ def prepare_generator_batch( ctx: DiffusionLossContext, batch: list[dict], *, + microbatch_id: int, + optim_step_idx: int, pad_to_len: int | None = None, ) -> PreparedBatch: - """The student's step ``i`` on its own rollout input ``x_i``, unguided.""" + """The student's step ``i`` on its own rollout input ``x_i``, unguided. + + The pairs carry their own noise, so ``microbatch_id`` and ``optim_step_idx`` are part of every prepare hook's + signature and unused here. + """ if len(ctx.models) != 1: raise ValueError("DMD2 currently supports a single DiT component") device = ctx.device @@ -211,6 +228,7 @@ def dmd2_loss_formula( old_pred: dict[str, torch.Tensor] | None, ref_pred: dict[str, torch.Tensor] | None, metrics: MetricBuffer, + optim_step_idx: int, write_old_log_prob: bool = False, old_log_prob_from_new: bool = False, ) -> torch.Tensor: diff --git a/miles/backends/fsdp_utils/loss_hub/flow_grpo.py b/miles/backends/fsdp_utils/loss_hub/flow_grpo.py index 3a17cb46a..050a6e431 100644 --- a/miles/backends/fsdp_utils/loss_hub/flow_grpo.py +++ b/miles/backends/fsdp_utils/loss_hub/flow_grpo.py @@ -18,9 +18,15 @@ def prepare_flow_grpo_batch( ctx: DiffusionLossContext, batch: list[dict], *, + microbatch_id: int, + optim_step_idx: int, pad_to_len: int | None = None, ) -> PreparedBatch: - """Stack SDE-pair fields and build CFG conditioning (guidance from args).""" + """Stack SDE-pair fields and build CFG conditioning (guidance from args). + + The pairs carry their own noise, so ``microbatch_id`` and ``optim_step_idx`` are part of every prepare hook's + signature and unused here. + """ args = ctx.args device = ctx.device config = ctx.train_pipeline_config @@ -114,6 +120,7 @@ def flow_grpo_loss_formula( old_pred: dict[str, torch.Tensor] | None, ref_pred: dict[str, torch.Tensor] | None, metrics: MetricBuffer, + optim_step_idx: int, write_old_log_prob: bool = False, old_log_prob_from_new: bool = False, ) -> torch.Tensor | None: diff --git a/miles/backends/fsdp_utils/loss_hub/nft.py b/miles/backends/fsdp_utils/loss_hub/nft.py index 4ef42999e..306e9c84c 100644 --- a/miles/backends/fsdp_utils/loss_hub/nft.py +++ b/miles/backends/fsdp_utils/loss_hub/nft.py @@ -24,9 +24,12 @@ def prepare_nft_batch( ctx: DiffusionLossContext, batch: list[dict], *, + microbatch_id: int, + optim_step_idx: int, pad_to_len: int | None = None, ) -> PreparedBatch: - """Corrupt clean x0 at each pair's sigma; CFG-free cond.""" + """Corrupt clean x0 at each pair's sigma; CFG-free cond. ``microbatch_id`` seeds the noise; ``optim_step_idx`` is + part of every prepare hook's signature and unused here.""" if len(ctx.models) != 1: raise ValueError("DiffusionNFT currently supports a single DiT component") device = ctx.device @@ -41,7 +44,7 @@ def prepare_nft_batch( pos_cond = config.collate_cond_for_sample_batch(pos_list, device, pad_to_len=pad_to_len) noise_generator = torch.Generator(device=device).manual_seed( - stable_hash("nft_corrupt", int(ctx.args.seed), ctx.rollout_id, ctx.microbatch_id, ctx.dp_rank) + stable_hash("nft_corrupt", int(ctx.args.seed), ctx.rollout_id, microbatch_id, ctx.dp_rank) ) xt = corrupt(x0, t, sample_noise(x0, generator=noise_generator)) # Rollout trajectories carry only the visual stream. @@ -111,6 +114,7 @@ def nft_loss_formula( old_pred: dict[str, torch.Tensor] | None, ref_pred: dict[str, torch.Tensor] | None, metrics: MetricBuffer, + optim_step_idx: int, write_old_log_prob: bool = False, old_log_prob_from_new: bool = False, ) -> torch.Tensor: diff --git a/miles/backends/fsdp_utils/loss_hub/sft.py b/miles/backends/fsdp_utils/loss_hub/sft.py index b17acfae7..bcab5c070 100644 --- a/miles/backends/fsdp_utils/loss_hub/sft.py +++ b/miles/backends/fsdp_utils/loss_hub/sft.py @@ -12,7 +12,7 @@ def select_component( - ctx: DiffusionLossContext, noise_schedule: FlowNoiseSchedule, device: torch.device + ctx: DiffusionLossContext, noise_schedule: FlowNoiseSchedule, device: torch.device, *, microbatch_id: int ) -> tuple[str, nn.Module, torch.Tensor]: """Pick one rank-aligned DiT component and the indices of the grid points it serves.""" config = ctx.train_pipeline_config @@ -25,7 +25,7 @@ def select_component( else: # dp_rank stays out of this seed: every rank must forward the same expert. expert_generator = torch.Generator().manual_seed( - stable_hash("expert", int(ctx.args.seed), ctx.rollout_id, ctx.microbatch_id) + stable_hash("expert", int(ctx.args.seed), ctx.rollout_id, microbatch_id) ) drawn = int(torch.randint(len(timesteps), (1,), generator=expert_generator)) component_name = component_for_timestep(timesteps[drawn]) @@ -38,6 +38,8 @@ def prepare_sft_batch( ctx: DiffusionLossContext, batch: list[dict], *, + microbatch_id: int, + optim_step_idx: int, pad_to_len: int | None = None, grid_index_range: tuple[int, int] | None = None, ) -> PreparedBatch: @@ -45,7 +47,8 @@ def prepare_sft_batch( The visual grid picks the DiT component and the index is drawn uniformly from the points it serves, within ``grid_index_range`` (inclusive) when given. Sharing the index pairs the streams' sigmas as inference steps them, - one step index read through each stream's shift. + one step index read through each stream's shift. ``microbatch_id`` seeds the draws; ``optim_step_idx`` is part of + every prepare hook's signature and unused here. """ device = ctx.device config = ctx.train_pipeline_config @@ -58,13 +61,15 @@ def prepare_sft_batch( stream_name: FlowNoiseSchedule.shifted(ctx.args.fsdp_flow_shift[stream_name], config.num_train_timesteps) for stream_name in stream_names } - component_name, model, visual_pool = select_component(ctx, noise_schedules["visual"], device) + component_name, model, visual_pool = select_component( + ctx, noise_schedules["visual"], device, microbatch_id=microbatch_id + ) if grid_index_range is not None: visual_pool = visual_pool[(visual_pool >= grid_index_range[0]) & (visual_pool <= grid_index_range[1])] # The visual stream keeps the single-stream seed, so single-stream runs draw as before; other streams add their # name, so adding a stream never changes another stream's noise. - seed_parts = ("sample", int(ctx.args.seed), ctx.rollout_id, ctx.microbatch_id, ctx.dp_rank) + seed_parts = ("sample", int(ctx.args.seed), ctx.rollout_id, microbatch_id, ctx.dp_rank) generators = { stream_name: torch.Generator(device=device).manual_seed( stable_hash(*seed_parts) if stream_name == "visual" else stable_hash(*seed_parts, stream_name) @@ -123,6 +128,7 @@ def sft_loss_formula( old_pred: dict[str, torch.Tensor] | None, ref_pred: dict[str, torch.Tensor] | None, metrics: MetricBuffer, + optim_step_idx: int, write_old_log_prob: bool = False, old_log_prob_from_new: bool = False, ) -> torch.Tensor: diff --git a/miles/backends/fsdp_utils/loss_hub/types.py b/miles/backends/fsdp_utils/loss_hub/types.py index fec342ea8..f25c62dc5 100644 --- a/miles/backends/fsdp_utils/loss_hub/types.py +++ b/miles/backends/fsdp_utils/loss_hub/types.py @@ -21,8 +21,6 @@ class DiffusionLossContext: forward_dtype: torch.dtype device: torch.device rollout_id: int = 0 - microbatch_id: int = 0 - optim_step_idx: int = 0 dp_rank: int = 0 reference_models: dict[str, torch.nn.Module] = field(default_factory=dict) teacher_models: dict[str, torch.nn.Module] = field(default_factory=dict) diff --git a/miles/utils/arguments.py b/miles/utils/arguments.py index 7690e4649..712c08aa3 100644 --- a/miles/utils/arguments.py +++ b/miles/utils/arguments.py @@ -960,7 +960,7 @@ def add_algo_arguments(parser): default=None, help=( "Dotted path to prepare hook " - "`fn(ctx, batch, *, pad_to_len=None) -> PreparedBatch`. " + "`fn(ctx, batch, *, microbatch_id, optim_step_idx, pad_to_len=None) -> PreparedBatch`. " "Builds DiT inputs; --loss-type custom_loss only, default is Flow-GRPO SDE-pair stacking." ), ) diff --git a/tests/fast-gpu/backends/fsdp_utils/_reference_models_worker.py b/tests/fast-gpu/backends/fsdp_utils/_reference_models_worker.py index f84fe1a57..2b33278fa 100644 --- a/tests/fast-gpu/backends/fsdp_utils/_reference_models_worker.py +++ b/tests/fast-gpu/backends/fsdp_utils/_reference_models_worker.py @@ -92,7 +92,14 @@ def check_roles(mesh, adapter_paths, reference_has_adapter, cpu_offload): target = reference_oracle(inputs) torch.testing.assert_close(teacher[component](inputs), teacher_oracle(inputs)) harness, observed = make_actor_forward_harness(actor, reference, component, inputs, "ref") - load_actor_forward_method()(harness, None, [], metrics=None).backward() + load_actor_forward_method()( + harness, + None, + [], + microbatch_id=0, + optim_step_idx=0, + metrics=None, + ).backward() expected_actor_output = oracle(inputs) (expected_actor_output - target).square().mean().backward() torch.testing.assert_close(observed["ref_pred"], target) @@ -116,7 +123,14 @@ def check_roles(mesh, adapter_paths, reference_has_adapter, cpu_offload): base_target = base_oracle(inputs) forward_count = actor[component].base_model.model.forward_count.item() harness, observed = make_actor_forward_harness(actor, {}, component, inputs, "lora_base") - load_actor_forward_method()(harness, None, [], metrics=None).backward() + load_actor_forward_method()( + harness, + None, + [], + microbatch_id=0, + optim_step_idx=0, + metrics=None, + ).backward() expected_actor_output = oracle(inputs) (expected_actor_output - base_target).square().mean().backward() torch.testing.assert_close(observed["ref_pred"], base_target) diff --git a/tests/fast/backends/fsdp_utils/test_h3_streams.py b/tests/fast/backends/fsdp_utils/test_h3_streams.py index a47a9e47a..94c53c24a 100644 --- a/tests/fast/backends/fsdp_utils/test_h3_streams.py +++ b/tests/fast/backends/fsdp_utils/test_h3_streams.py @@ -104,7 +104,7 @@ def test_t2va_prediction_matches_the_sft_target_and_skips_padding_rows(): device=torch.device("cpu"), ) batch = [{"latent": {"visual": torch.ones(3, 96)}, "cond_kwargs": cond}] - prepared = prepare_sft_batch(context, batch) + prepared = prepare_sft_batch(context, batch, microbatch_id=0, optim_step_idx=0) prediction = config.compute_noise_pred( model=context.models["transformer"], latents_input=prepared.latents, @@ -125,7 +125,14 @@ def test_t2va_prediction_matches_the_sft_target_and_skips_padding_rows(): assert inputs["timestep_indices"].shape == (7,) metrics = new_metric_buffer(None, torch.device("cpu"), ["transformer"], sigma_buckets=5) loss = sft_loss_formula( - context, batch, prepared, new_pred=prediction, old_pred=None, ref_pred=None, metrics=metrics + context, + batch, + prepared, + new_pred=prediction, + old_pred=None, + ref_pred=None, + metrics=metrics, + optim_step_idx=0, ) assert torch.isfinite(loss) and loss.item() > 0 @@ -405,7 +412,7 @@ def test_real_tiny_diffusers_h3_joint_sft_forward_and_backward(forward_dtype): forward_dtype=forward_dtype, device=torch.device("cpu"), ) - prepared = prepare_sft_batch(context, batch) + prepared = prepare_sft_batch(context, batch, microbatch_id=0, optim_step_idx=0) autocast_enabled = forward_dtype != torch.float32 and config.enable_autocast with torch.autocast("cpu", dtype=forward_dtype, enabled=autocast_enabled): prediction = config.compute_noise_pred( @@ -426,7 +433,14 @@ def test_real_tiny_diffusers_h3_joint_sft_forward_and_backward(forward_dtype): } metrics = new_metric_buffer(None, torch.device("cpu"), ["transformer_ref"], sigma_buckets=5) loss = sft_loss_formula( - context, batch, prepared, new_pred=prediction, old_pred=None, ref_pred=None, metrics=metrics + context, + batch, + prepared, + new_pred=prediction, + old_pred=None, + ref_pred=None, + metrics=metrics, + optim_step_idx=0, ) assert torch.isfinite(loss) and loss.item() > 0 assert prepared.extras["target"]["visual"].dtype == torch.float32 diff --git a/tests/fast/backends/fsdp_utils/test_loss_hub_dmd2.py b/tests/fast/backends/fsdp_utils/test_loss_hub_dmd2.py index eca56850e..c440dc385 100644 --- a/tests/fast/backends/fsdp_utils/test_loss_hub_dmd2.py +++ b/tests/fast/backends/fsdp_utils/test_loss_hub_dmd2.py @@ -138,12 +138,12 @@ def _ctx(teacher_guidance_scale=3.0, critic_scale=1.0, teacher_scale=1.0): def _critic_step(ctx, pairs, optim_step_idx, metrics=None): """One critic optimizer step as _train_core runs it: prepare, the critic's training forward, the loss hook.""" - ctx.optim_step_idx = optim_step_idx steps = [] for start in range(0, len(pairs), ctx.args.micro_batch_size): batch = pairs[start : start + ctx.args.micro_batch_size] - ctx.microbatch_id = optim_step_idx * 10 + start - prepared = dmd2.prepare_critic_batch(ctx, batch) + prepared = dmd2.prepare_critic_batch( + ctx, batch, microbatch_id=optim_step_idx * 10 + start, optim_step_idx=optim_step_idx + ) new_pred = ctx.train_pipeline_config.compute_noise_pred( model=prepared.model, latents_input=prepared.latents, @@ -157,7 +157,14 @@ def _critic_step(ctx, pairs, optim_step_idx, metrics=None): true_cfg_scale=None, ) loss = dmd2.critic_loss_formula( - ctx, batch, prepared, new_pred=new_pred, old_pred=None, ref_pred=None, metrics=metrics or _Metrics() + ctx, + batch, + prepared, + new_pred=new_pred, + old_pred=None, + ref_pred=None, + metrics=metrics or _Metrics(), + optim_step_idx=optim_step_idx, ) steps.append((batch, prepared, new_pred, loss)) return steps @@ -179,9 +186,8 @@ def test_critic_batch_is_the_sft_batch_on_the_student_x0(): pairs = _pairs(3) for optim_step_idx in range(CRITIC_STEPS - 1): - ctx.optim_step_idx = optim_step_idx - critic_batch = dmd2.prepare_critic_batch(ctx, pairs) - sft_batch = prepare_sft_batch(ctx, _sft_pairs(ctx, pairs)) + critic_batch = dmd2.prepare_critic_batch(ctx, pairs, microbatch_id=0, optim_step_idx=optim_step_idx) + sft_batch = prepare_sft_batch(ctx, _sft_pairs(ctx, pairs), microbatch_id=0, optim_step_idx=optim_step_idx) assert critic_batch.model is ctx.models["transformer"] for field in ("latents", "timesteps", "timesteps_for_model"): @@ -194,10 +200,12 @@ def test_critic_batch_is_the_sft_batch_on_the_student_x0(): def test_last_step_draws_from_the_scoring_range(): ctx = _ctx() pairs = _pairs(256) - ctx.optim_step_idx = CRITIC_STEPS - 1 + last_step = CRITIC_STEPS - 1 - critic_batch = dmd2.prepare_critic_batch(ctx, pairs) - sft_batch = prepare_sft_batch(ctx, _sft_pairs(ctx, pairs), grid_index_range=(20, 980)) + critic_batch = dmd2.prepare_critic_batch(ctx, pairs, microbatch_id=0, optim_step_idx=last_step) + sft_batch = prepare_sft_batch( + ctx, _sft_pairs(ctx, pairs), microbatch_id=0, optim_step_idx=last_step, grid_index_range=(20, 980) + ) assert torch.equal(critic_batch.latents["visual"], sft_batch.latents["visual"]) assert torch.equal(critic_batch.extras["target"]["visual"], sft_batch.extras["target"]["visual"]) @@ -205,20 +213,21 @@ def test_last_step_draws_from_the_scoring_range(): sigmas = critic_batch.extras["sigmas"]["visual"] assert set(sigmas.tolist()) <= set(grid[20:981].tolist()) # The same draw without the range leaves it, so the restriction is exercised. - assert not set(prepare_sft_batch(ctx, _sft_pairs(ctx, pairs)).extras["sigmas"]["visual"].tolist()) <= set( - grid[20:981].tolist() - ) + unrestricted = prepare_sft_batch(ctx, _sft_pairs(ctx, pairs), microbatch_id=0, optim_step_idx=last_step) + assert not set(unrestricted.extras["sigmas"]["visual"].tolist()) <= set(grid[20:981].tolist()) def test_score_sigma_range_bounds_the_unshifted_sigma(): ctx = _ctx() ctx.args.dmd2_score_sigma_range = [0.1, 0.5] pairs = _pairs(256) - ctx.optim_step_idx = CRITIC_STEPS - 1 + last_step = CRITIC_STEPS - 1 - critic_batch = dmd2.prepare_critic_batch(ctx, pairs) + critic_batch = dmd2.prepare_critic_batch(ctx, pairs, microbatch_id=0, optim_step_idx=last_step) # Grid index i carries the unshifted sigma 1 - i / 1000, so [0.1, 0.5] is grid points [500, 900]. - sft_batch = prepare_sft_batch(ctx, _sft_pairs(ctx, pairs), grid_index_range=(500, 900)) + sft_batch = prepare_sft_batch( + ctx, _sft_pairs(ctx, pairs), microbatch_id=0, optim_step_idx=last_step, grid_index_range=(500, 900) + ) sigmas = critic_batch.extras["sigmas"]["visual"] assert torch.equal(sigmas, sft_batch.extras["sigmas"]["visual"]) @@ -233,7 +242,14 @@ def test_critic_loss_is_the_sft_loss(): sft_metrics = _Metrics() for batch, prepared, new_pred, loss in _critic_step(ctx, _pairs(3), optim_step_idx, metrics): sft_loss = sft_loss_formula( - ctx, batch, prepared, new_pred=new_pred, old_pred=None, ref_pred=None, metrics=sft_metrics + ctx, + batch, + prepared, + new_pred=new_pred, + old_pred=None, + ref_pred=None, + metrics=sft_metrics, + optim_step_idx=optim_step_idx, ) assert torch.equal(loss, sft_loss) assert metrics.seen == sft_metrics.seen @@ -371,12 +387,21 @@ def _metrics(): def _loss(ctx, pairs, x0): """dmd2_loss_formula with the student predicting ``x0`` from each pair's rollout input.""" - prepared = dmd2.prepare_generator_batch(ctx, pairs) + prepared = dmd2.prepare_generator_batch(ctx, pairs, microbatch_id=0, optim_step_idx=0) sigmas = prepared.extras["sigmas"].view(-1, 1, 1, 1) new_pred = {"visual": (prepared.latents["visual"] - x0) / sigmas} metrics = _metrics() return ( - dmd2.dmd2_loss_formula(ctx, pairs, prepared, new_pred=new_pred, old_pred=None, ref_pred=None, metrics=metrics), + dmd2.dmd2_loss_formula( + ctx, + pairs, + prepared, + new_pred=new_pred, + old_pred=None, + ref_pred=None, + metrics=metrics, + optim_step_idx=0, + ), metrics, ) @@ -392,7 +417,7 @@ def test_generator_batch_is_the_student_step_on_its_input(): ctx = _ctx() pairs = _generator_pairs(2) - prepared = dmd2.prepare_generator_batch(ctx, pairs) + prepared = dmd2.prepare_generator_batch(ctx, pairs, microbatch_id=0, optim_step_idx=0) assert prepared.model is ctx.models["transformer"] assert torch.equal(prepared.latents["visual"], torch.stack([pair["latent"] for pair in pairs]).float()) @@ -406,7 +431,7 @@ def test_generator_needs_a_single_component(): ctx = _ctx() ctx.models["transformer_2"] = ctx.models["transformer"] with pytest.raises(ValueError, match="single DiT component"): - dmd2.prepare_generator_batch(ctx, _generator_pairs(1)) + dmd2.prepare_generator_batch(ctx, _generator_pairs(1), microbatch_id=0, optim_step_idx=0) def test_surrogate_gradient_matches_the_reference(): 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 c3e596099..e38832bb8 100644 --- a/tests/fast/backends/fsdp_utils/test_loss_hub_nft.py +++ b/tests/fast/backends/fsdp_utils/test_loss_hub_nft.py @@ -89,6 +89,7 @@ def loss(kl_beta): old_pred=old_pred, ref_pred={"visual": new_pred["visual"] - 1.0}, metrics=metrics, + optim_step_idx=0, ) torch.testing.assert_close(loss(0.5) - loss(0.0), torch.tensor(0.5 * 2)) @@ -240,7 +241,7 @@ class _Env: pos_cond_kwargs = None neg_cond_kwargs = None - def _ctx(self, config, microbatch_id=0): + def _ctx(self, config): return DiffusionLossContext( models={"transformer": torch.nn.Identity()}, train_pipeline_config=config, @@ -248,7 +249,6 @@ def _ctx(self, config, microbatch_id=0): args=Namespace(seed=42), forward_dtype=torch.float32, device=torch.device("cpu"), - microbatch_id=microbatch_id, ) def _batch(self): @@ -271,18 +271,18 @@ def process_sigma_as_timesteps_input(self, sigmas): seen["sigmas"] = sigmas.clone() return sigmas - prepare_nft_batch(self._ctx(_Recording()), self._batch()) + prepare_nft_batch(self._ctx(_Recording()), self._batch(), microbatch_id=0, optim_step_idx=0) assert torch.equal(seen["sigmas"], torch.tensor(self.SIGMAS)) def test_sd3_style_family_gets_sigma_times_num_train_timesteps(self): - prepared = prepare_nft_batch(self._ctx(_Sd3StyleConfig()), self._batch()) + prepared = prepare_nft_batch(self._ctx(_Sd3StyleConfig()), self._batch(), microbatch_id=0, optim_step_idx=0) assert torch.equal(prepared.timesteps["visual"], torch.tensor(self.SIGMAS)) assert torch.equal( prepared.timesteps_for_model["visual"], torch.tensor(self.SIGMAS) * float(_StubConfig.num_train_timesteps) ) def test_qwen_style_family_gets_the_sigma_bit_exactly(self): - prepared = prepare_nft_batch(self._ctx(_QwenStyleConfig()), self._batch()) + prepared = prepare_nft_batch(self._ctx(_QwenStyleConfig()), self._batch(), microbatch_id=0, optim_step_idx=0) # equal, not allclose: the wrong hook would still pass allclose. assert torch.equal(prepared.timesteps_for_model["visual"], torch.tensor(self.SIGMAS)) @@ -354,12 +354,14 @@ def test_each_sample_draws_its_own_permutation(self): def test_corruption_noise_reproduces(self): ctx = TestPrepareNftBatch()._ctx(_Sd3StyleConfig()) batch = TestPrepareNftBatch()._batch() - first = prepare_nft_batch(ctx, batch) - second = prepare_nft_batch(ctx, batch) + first = prepare_nft_batch(ctx, batch, microbatch_id=0, optim_step_idx=0) + second = prepare_nft_batch(ctx, batch, microbatch_id=0, optim_step_idx=0) assert torch.equal(first.latents["visual"], second.latents["visual"]) def test_a_different_microbatch_draws_different_noise(self): harness = TestPrepareNftBatch() - first = prepare_nft_batch(harness._ctx(_Sd3StyleConfig()), harness._batch()) - second = prepare_nft_batch(harness._ctx(_Sd3StyleConfig(), microbatch_id=1), harness._batch()) + first = prepare_nft_batch(harness._ctx(_Sd3StyleConfig()), harness._batch(), microbatch_id=0, optim_step_idx=0) + second = prepare_nft_batch( + harness._ctx(_Sd3StyleConfig()), harness._batch(), microbatch_id=1, optim_step_idx=0 + ) assert not torch.equal(first.latents["visual"], second.latents["visual"]) 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 f04403a15..5d51f4079 100644 --- a/tests/fast/backends/fsdp_utils/test_loss_hub_selection.py +++ b/tests/fast/backends/fsdp_utils/test_loss_hub_selection.py @@ -80,7 +80,7 @@ def test_the_table_has_no_other_entries(): def test_custom_loss_loads_every_path(): - def prepare(ctx, batch, *, pad_to_len=None): + def prepare(ctx, batch, *, microbatch_id, optim_step_idx, pad_to_len=None): pass def formula(ctx, batch, prepared, **kwargs): diff --git a/tests/fast/backends/fsdp_utils/test_loss_hub_sft.py b/tests/fast/backends/fsdp_utils/test_loss_hub_sft.py index d3b7e3afb..813ceb01c 100644 --- a/tests/fast/backends/fsdp_utils/test_loss_hub_sft.py +++ b/tests/fast/backends/fsdp_utils/test_loss_hub_sft.py @@ -4,7 +4,7 @@ │ prepare_sft_batch: grid ──► FlowNoiseSchedule.shifted(--fsdp-flow-shift[name]) - select_component(visual grid), once, rank-aligned ──► DiT component + the visual grid points it serves + select_component(visual grid, microbatch_id), once, rank-aligned ──► DiT component + the visual grid points it serves each stream gets its own seeded generator (visual: the single-stream seed; other streams add their name to it) grid index ──► one per pair, uniform over the component's points, drawn by the visual generator @@ -77,7 +77,7 @@ def _noise_schedule(): return FlowNoiseSchedule(sigmas * NUM_TRAIN_TIMESTEPS, torch.cat([sigmas, torch.zeros(1)])) -def _ctx(models, rollout_id=3, microbatch_id=0, dp_rank=0, config=None): +def _ctx(models, rollout_id=3, dp_rank=0, config=None): return DiffusionLossContext( models=models, train_pipeline_config=config if config is not None else _Config(), @@ -91,7 +91,6 @@ def _ctx(models, rollout_id=3, microbatch_id=0, dp_rank=0, config=None): forward_dtype=torch.float32, device=torch.device("cpu"), rollout_id=rollout_id, - microbatch_id=microbatch_id, dp_rank=dp_rank, ) @@ -124,7 +123,7 @@ def test_corruption_and_target_identity(self): torch.manual_seed(0) ctx = _ctx({"transformer": nn.Identity()}) batch = _batch() - prepared = prepare_sft_batch(ctx, batch) + prepared = prepare_sft_batch(ctx, batch, microbatch_id=0, optim_step_idx=0) x0 = torch.stack([pair["latent"]["visual"] for pair in batch]).float() sigma = (prepared.timesteps["visual"] / NUM_TRAIN_TIMESTEPS).view(-1, 1, 1, 1, 1) @@ -136,7 +135,7 @@ def test_corruption_and_target_identity(self): def test_single_model_serves_the_whole_grid(self): ctx = _ctx({"transformer": nn.Identity()}, config=_SingleConfig()) - _, _, pool = select_component(ctx, _noise_schedule(), torch.device("cpu")) + _, _, pool = select_component(ctx, _noise_schedule(), torch.device("cpu"), microbatch_id=0) assert torch.equal(pool, torch.arange(NUM_GRID)) def test_single_wan_expert_serves_only_its_timesteps(self): @@ -144,7 +143,7 @@ def test_single_wan_expert_serves_only_its_timesteps(self): timesteps = _noise_schedule().timesteps for component_name in ("transformer", "transformer_2"): ctx = _ctx({component_name: nn.Identity()}, config=config) - name, _, pool = select_component(ctx, _noise_schedule(), torch.device("cpu")) + name, _, pool = select_component(ctx, _noise_schedule(), torch.device("cpu"), microbatch_id=0) expected = [ i for i, timestep in enumerate(timesteps) @@ -160,8 +159,7 @@ def test_dual_expert_micro_batch_is_phase_pure(self): noise_schedule = _noise_schedule() picked = set() for call in range(20): - ctx.microbatch_id = call - name, model, pool = select_component(ctx, noise_schedule, torch.device("cpu")) + name, model, pool = select_component(ctx, noise_schedule, torch.device("cpu"), microbatch_id=call) picked.add(name) assert model is models[name] for i in pool.tolist(): @@ -174,11 +172,11 @@ def test_prepare_is_independent_of_global_rng_state(self): torch.manual_seed(0) global_state = torch.get_rng_state() - first = prepare_sft_batch(_ctx({"transformer": nn.Identity()}), batch) + first = prepare_sft_batch(_ctx({"transformer": nn.Identity()}), batch, microbatch_id=0, optim_step_idx=0) assert torch.equal(torch.get_rng_state(), global_state) torch.rand(1000) - second = prepare_sft_batch(_ctx({"transformer": nn.Identity()}), batch) + second = prepare_sft_batch(_ctx({"transformer": nn.Identity()}), batch, microbatch_id=0, optim_step_idx=0) assert torch.equal(first.timesteps["visual"], second.timesteps["visual"]) assert torch.equal(first.latents["visual"], second.latents["visual"]) assert torch.equal(_visual_target(first), _visual_target(second)) @@ -188,7 +186,7 @@ def test_visual_stream_draws_what_the_single_stream_seed_draws(self): # the draws single-stream SFT made before latents were keyed by stream, rebuilt by hand. ctx = _ctx({"transformer": nn.Identity()}) batch = _batch() - prepared = prepare_sft_batch(ctx, batch) + prepared = prepare_sft_batch(ctx, batch, microbatch_id=0, optim_step_idx=0) generator = torch.Generator().manual_seed(stable_hash("sample", 42, 3, 0, 0)) noise_schedule = FlowNoiseSchedule.shifted(FLOW_SHIFT, NUM_TRAIN_TIMESTEPS) @@ -201,17 +199,21 @@ def test_visual_stream_draws_what_the_single_stream_seed_draws(self): def test_samples_within_microbatch_use_different_noise(self): batch = _batch(bsz=4) - prepared = prepare_sft_batch(_ctx({"transformer": nn.Identity()}), batch) + prepared = prepare_sft_batch(_ctx({"transformer": nn.Identity()}), batch, microbatch_id=0, optim_step_idx=0) x0 = torch.stack([pair["latent"]["visual"] for pair in batch]).float() noise = _visual_target(prepared) + x0 assert all(not torch.equal(noise[0], noise[i]) for i in range(1, len(batch))) def test_identity_changes_draws(self): batch = _batch() - base = prepare_sft_batch(_ctx({"transformer": nn.Identity()}), batch) - other_rollout = prepare_sft_batch(_ctx({"transformer": nn.Identity()}, rollout_id=4), batch) - other_slot = prepare_sft_batch(_ctx({"transformer": nn.Identity()}, microbatch_id=1), batch) - other_dp_rank = prepare_sft_batch(_ctx({"transformer": nn.Identity()}, dp_rank=1), batch) + base = prepare_sft_batch(_ctx({"transformer": nn.Identity()}), batch, microbatch_id=0, optim_step_idx=0) + other_rollout = prepare_sft_batch( + _ctx({"transformer": nn.Identity()}, rollout_id=4), batch, microbatch_id=0, optim_step_idx=0 + ) + other_slot = prepare_sft_batch(_ctx({"transformer": nn.Identity()}), batch, microbatch_id=1, optim_step_idx=0) + other_dp_rank = prepare_sft_batch( + _ctx({"transformer": nn.Identity()}, dp_rank=1), batch, microbatch_id=0, optim_step_idx=0 + ) for other in (other_rollout, other_slot, other_dp_rank): assert not torch.equal(_visual_target(base), _visual_target(other)) @@ -219,8 +221,8 @@ def test_dual_expert_choice_is_rank_aligned(self): models = {"transformer": nn.Identity(), "transformer_2": nn.Identity()} for slot in range(10): # Different DP ranks choose the same expert but use independent sample RNG. - a = prepare_sft_batch(_ctx(models, microbatch_id=slot, dp_rank=0), _batch()) - b = prepare_sft_batch(_ctx(models, microbatch_id=slot, dp_rank=1), _batch()) + a = prepare_sft_batch(_ctx(models, dp_rank=0), _batch(), microbatch_id=slot, optim_step_idx=0) + b = prepare_sft_batch(_ctx(models, dp_rank=1), _batch(), microbatch_id=slot, optim_step_idx=0) assert a.component_name == b.component_name assert not torch.equal(_visual_target(a), _visual_target(b)) @@ -229,7 +231,9 @@ def test_prepare_draws_from_the_flow_shift_grid(self): noise_schedule = FlowNoiseSchedule.shifted(3.0, 4) torch.testing.assert_close(noise_schedule.sigmas, torch.tensor([1.0, 0.9, 0.75, 0.5, 0.0])) torch.testing.assert_close(noise_schedule.timesteps, torch.tensor([4.0, 3.6, 3.0, 2.0])) - prepared = prepare_sft_batch(_ctx({"transformer": nn.Identity()}), _batch(bsz=16)) + prepared = prepare_sft_batch( + _ctx({"transformer": nn.Identity()}), _batch(bsz=16), microbatch_id=0, optim_step_idx=0 + ) grid = FlowNoiseSchedule.shifted(FLOW_SHIFT, NUM_TRAIN_TIMESTEPS) assert set(prepared.extras["sigmas"]["visual"].tolist()) <= set(grid.sigmas[:-1].tolist()) assert set(prepared.timesteps["visual"].tolist()) <= set(grid.timesteps.tolist()) @@ -240,10 +244,17 @@ def _loss(self, prediction_offset, metrics, log_loss_sigma_bucket=5): ctx = _ctx({"transformer": nn.Identity()}) ctx.args.log_loss_sigma_bucket = log_loss_sigma_bucket batch = _batch() - prepared = prepare_sft_batch(ctx, batch) + prepared = prepare_sft_batch(ctx, batch, microbatch_id=0, optim_step_idx=0) new_pred = {"visual": _visual_target(prepared) + prediction_offset} return prepared, sft_loss_formula( - ctx, batch, prepared, new_pred=new_pred, old_pred=None, ref_pred=None, metrics=metrics + ctx, + batch, + prepared, + new_pred=new_pred, + old_pred=None, + ref_pred=None, + metrics=metrics, + optim_step_idx=0, ) def test_zero_loss_on_exact_velocity(self): @@ -295,7 +306,9 @@ class TestJointStreams: def test_each_stream_draws_from_its_own_flow_shift_grid(self): # --fsdp-flow-shift visual=3,audio=1: each stream's sigmas lie on its own grid, not on the other's. batch = _joint_batch(16) - prepared = prepare_sft_batch(_ctx({"transformer": nn.Identity()}, config=_SingleConfig()), batch) + prepared = prepare_sft_batch( + _ctx({"transformer": nn.Identity()}, config=_SingleConfig()), batch, microbatch_id=0, optim_step_idx=0 + ) assert set(prepared.latents) == {"visual", "audio"} grids = { name: set(FlowNoiseSchedule.shifted(FLOW_SHIFTS[name], NUM_TRAIN_TIMESTEPS).sigmas[:-1].tolist()) @@ -316,14 +329,14 @@ def test_streams_share_the_grid_index_but_not_the_noise(self): batch = _joint_batch(32) for pair in batch: pair["latent"]["audio"] = pair["latent"]["visual"].clone() - first = prepare_sft_batch(ctx, batch) + first = prepare_sft_batch(ctx, batch, microbatch_id=0, optim_step_idx=0) grids = {name: FlowNoiseSchedule.shifted(FLOW_SHIFTS[name], NUM_TRAIN_TIMESTEPS) for name in FLOW_SHIFTS} idx = torch.searchsorted(-grids["visual"].sigmas.float(), -first.extras["sigmas"]["visual"]) assert torch.equal(first.extras["sigmas"]["audio"], grids["audio"].sigmas.float()[idx]) assert not torch.equal(first.extras["target"]["visual"], first.extras["target"]["audio"]) for pair in batch: pair["latent"]["action"] = torch.ones(10, 7) - second = prepare_sft_batch(ctx, batch) + second = prepare_sft_batch(ctx, batch, microbatch_id=0, optim_step_idx=0) for name in ("visual", "audio"): assert torch.equal(first.extras["target"][name], second.extras["target"][name]) assert torch.equal(first.timesteps[name], second.timesteps[name]) @@ -332,14 +345,21 @@ def test_loss_averages_each_stream_over_its_own_size(self): # visual (96 elements) off by 1, audio (12 elements) off by 2: per pair 1 + 4, not a size-weighted mix. ctx = _ctx({"transformer": nn.Identity()}, config=_SingleConfig()) batch = _joint_batch(2) - prepared = prepare_sft_batch(ctx, batch) + prepared = prepare_sft_batch(ctx, batch, microbatch_id=0, optim_step_idx=0) predictions = { "visual": (prepared.extras["target"]["visual"] + 1.0).requires_grad_(), "audio": (prepared.extras["target"]["audio"] + 2.0).requires_grad_(), } metrics = _Metrics() loss = sft_loss_formula( - ctx, batch, prepared, new_pred=predictions, old_pred=None, ref_pred=None, metrics=metrics + ctx, + batch, + prepared, + new_pred=predictions, + old_pred=None, + ref_pred=None, + metrics=metrics, + optim_step_idx=0, ) assert loss.item() == pytest.approx(10.0) loss.backward() @@ -354,13 +374,15 @@ def test_joint_metrics_split_by_stream_and_bucket_by_own_sigma(self): ctx = _ctx({"transformer": nn.Identity()}, config=_SingleConfig()) batch = _joint_batch(2) - prepared = prepare_sft_batch(ctx, batch) + prepared = prepare_sft_batch(ctx, batch, microbatch_id=0, optim_step_idx=0) predictions = { "visual": prepared.extras["target"]["visual"] + 1.0, "audio": prepared.extras["target"]["audio"] + 2.0, } metrics = _Metrics() - sft_loss_formula(ctx, batch, prepared, new_pred=predictions, old_pred=None, ref_pred=None, metrics=metrics) + sft_loss_formula( + ctx, batch, prepared, new_pred=predictions, old_pred=None, ref_pred=None, metrics=metrics, optim_step_idx=0 + ) assert metrics.seen["loss"] == (10.0, 2) assert metrics.seen["loss_visual"] == (2.0, 2) assert metrics.seen["loss_audio"] == (8.0, 2) @@ -380,7 +402,7 @@ def test_a_stream_the_config_does_not_predict_adds_no_loss(self): # H3 Ref2VA on a silent target: the audio stream is noised and fed to the DiT, but only visual is predicted. ctx = _ctx({"transformer": nn.Identity()}, config=_SingleConfig()) batch = _joint_batch(2) - prepared = prepare_sft_batch(ctx, batch) + prepared = prepare_sft_batch(ctx, batch, microbatch_id=0, optim_step_idx=0) loss = sft_loss_formula( ctx, batch, @@ -389,6 +411,7 @@ def test_a_stream_the_config_does_not_predict_adds_no_loss(self): old_pred=None, ref_pred=None, metrics=_Metrics(), + optim_step_idx=0, ) assert loss.item() == pytest.approx(2.0) @@ -397,7 +420,7 @@ def test_a_stream_left_out_of_supervised_streams_adds_no_loss(self): ctx = _ctx({"transformer": nn.Identity()}, config=_SingleConfig()) ctx.args.fsdp_supervised_streams = ["visual"] batch = _joint_batch(2) - prepared = prepare_sft_batch(ctx, batch) + prepared = prepare_sft_batch(ctx, batch, microbatch_id=0, optim_step_idx=0) metrics = _Metrics() loss = sft_loss_formula( ctx, @@ -410,6 +433,7 @@ def test_a_stream_left_out_of_supervised_streams_adds_no_loss(self): old_pred=None, ref_pred=None, metrics=metrics, + optim_step_idx=0, ) assert loss.item() == pytest.approx(2.0) # One supervised stream: its loss is the total, and only its own buckets appear. @@ -420,8 +444,10 @@ def test_visual_stream_selects_a_rank_aligned_expert(self): models = {"transformer": nn.Identity(), "transformer_2": nn.Identity()} batch = _joint_batch(4) for slot in range(5): - contexts = [_ctx(models, microbatch_id=slot, dp_rank=rank) for rank in (0, 1)] - first, second = [prepare_sft_batch(context, batch) for context in contexts] + contexts = [_ctx(models, dp_rank=rank) for rank in (0, 1)] + first, second = [ + prepare_sft_batch(context, batch, microbatch_id=slot, optim_step_idx=0) for context in contexts + ] assert first.component_name == second.component_name for timestep in first.timesteps["visual"]: component = contexts[0].train_pipeline_config.component_for_timestep(float(timestep)) @@ -430,16 +456,23 @@ def test_visual_stream_selects_a_rank_aligned_expert(self): def test_rejects_misshaped_predictions(self): ctx = _ctx({"transformer": nn.Identity()}, config=_SingleConfig()) batch = _joint_batch(1) - prepared = prepare_sft_batch(ctx, batch) + prepared = prepare_sft_batch(ctx, batch, microbatch_id=0, optim_step_idx=0) predictions = dict(prepared.extras["target"]) predictions["audio"] = predictions["audio"][0] with pytest.raises(ValueError, match="prediction shape"): sft_loss_formula( - ctx, batch, prepared, new_pred=predictions, old_pred=None, ref_pred=None, metrics=_Metrics() + ctx, + batch, + prepared, + new_pred=predictions, + old_pred=None, + ref_pred=None, + metrics=_Metrics(), + optim_step_idx=0, ) def test_rejects_different_stream_sets_in_one_microbatch(self): batch = _joint_batch(2) del batch[1]["latent"]["audio"] with pytest.raises(ValueError, match="latent streams"): - prepare_sft_batch(_ctx({"transformer": nn.Identity()}), batch) + prepare_sft_batch(_ctx({"transformer": nn.Identity()}), batch, microbatch_id=0, optim_step_idx=0) diff --git a/tests/fast/backends/fsdp_utils/test_reference_models.py b/tests/fast/backends/fsdp_utils/test_reference_models.py index 8f6f2ad99..8d9674814 100644 --- a/tests/fast/backends/fsdp_utils/test_reference_models.py +++ b/tests/fast/backends/fsdp_utils/test_reference_models.py @@ -259,7 +259,14 @@ def test_loaded_reference_and_teacher_are_independent_and_frozen( teacher_output = teacher[component](inputs) assert not torch.equal(target, teacher_output) harness, observed = make_actor_forward_harness(actor, reference, component, inputs, "ref") - load_actor_forward_method()(harness, None, [], metrics=None).backward() + load_actor_forward_method()( + harness, + None, + [], + microbatch_id=0, + optim_step_idx=0, + metrics=None, + ).backward() oracle_output = oracle(inputs) (oracle_output - target).square().mean().backward() torch.testing.assert_close(observed["new_pred"], oracle_output) @@ -299,7 +306,14 @@ def test_lora_base_forward_restores_adapters_and_actor_gradients(tmp_path, unsha with torch.no_grad(): target = base(inputs) harness, observed = make_actor_forward_harness(actor, {}, component, inputs, "lora_base") - load_actor_forward_method()(harness, None, [], metrics=None).backward() + load_actor_forward_method()( + harness, + None, + [], + microbatch_id=0, + optim_step_idx=0, + metrics=None, + ).backward() oracle_output = oracle(inputs) (oracle_output - target).square().mean().backward() torch.testing.assert_close(observed["ref_pred"], target) @@ -353,7 +367,14 @@ def test_lora_base_reference_keeps_adapter_gradients_on_fsdp_shards(): harness, _ = make_actor_forward_harness( {"transformer": model}, {}, "transformer", torch.ones(2, 3), "lora_base" ) - forward(harness, None, [], metrics=None).backward() + forward( + harness, + None, + [], + microbatch_id=0, + optim_step_idx=0, + metrics=None, + ).backward() for name, parameter in adapter_parameters.items(): assert parameter.requires_grad and parameter.grad is not None, (step, name) model.zero_grad(set_to_none=True) @@ -390,7 +411,14 @@ def test_nft_gets_ema_as_old_and_lora_base_as_kl_reference(tmp_path, unsharded_m harness, observed = make_actor_forward_harness( actor, {}, component, inputs, "lora_base", loss_type="nft", ema_optimizer=ema_optimizer ) - load_actor_forward_method()(harness, None, [], metrics=None) + load_actor_forward_method()( + harness, + None, + [], + microbatch_id=0, + optim_step_idx=0, + metrics=None, + ) torch.testing.assert_close(observed["new_pred"], expected_new) torch.testing.assert_close(observed["old_pred"], expected_old) torch.testing.assert_close(observed["ref_pred"], expected_ref) 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 ee94596ff..11e119410 100644 --- a/tests/fast/backends/fsdp_utils/test_train_input_hook.py +++ b/tests/fast/backends/fsdp_utils/test_train_input_hook.py @@ -6,8 +6,11 @@ preprocessed pairs --> train-output hook (the same ctx) no hook --> the converted train pairs, as before +The trunk numbers each forward: ``microbatch_id`` counts the rollout's micro-batches, ``optim_step_idx`` is the +window; the old-log-prob recompute of windows 1.. reuses their training forwards' numbers. + The production _train_core runs on CPU with the forward, metrics and rank checks replaced; the -optimizer step is skipped, so only the pairs and ctx each stage receives are observed. +optimizer step is skipped, so only the pairs, ctx and numbers each stage receives are observed. """ from tests.ci.ci_register import register_cpu_ci @@ -51,7 +54,7 @@ def _load_train_core(): return namespace["_train_core"] -def _actor(train_input, train_output, forwarded): +def _actor(train_input, train_output, forwarded, **args): return SimpleNamespace( models={}, reference_models={}, @@ -62,10 +65,10 @@ def _actor(train_input, train_output, forwarded): num_steps_per_rollout=2, micro_batch_size=1, loss_type="policy_loss", - diffusion_recompute_old_log_prob=False, debug_skip_optimizer_step=True, log_loss_sigma_bucket=0, diffusion_num_steps=4, + **{"diffusion_recompute_old_log_prob": False, **args}, ), _forward_dtype=torch.float32, parallel_state=SimpleNamespace(dp_rank=0, dp_group=None), @@ -73,7 +76,11 @@ def _actor(train_input, train_output, forwarded): optimizer=SimpleNamespace(zero_grad=lambda set_to_none: None), global_step=0, _maybe_legacy_window_pad_len=lambda train_pairs, microbatch_ranges: None, - _forward_train_pair_batch=lambda ctx, chunk, **kwargs: forwarded.append((ctx.microbatch_id, chunk)), + _forward_train_pair_batch=lambda ctx, chunk, **kwargs: ( + forwarded.append( + (kwargs["microbatch_id"], kwargs["optim_step_idx"], kwargs.get("write_old_log_prob", False), chunk) + ), + ), _log_metrics=lambda rollout_id, metrics, step: None, ) @@ -104,7 +111,13 @@ def train_input(ctx, train_pairs): preprocessed = [{"sample_index": index, "score": scores[index]} for index in (1, 2, 4, 5)] assert seen_by_input == [(ctx, pairs)] assert (ctx.rollout_id, ctx.external_data) == (3, {"critic": scores}) - assert forwarded == [(microbatch_id, [pair]) for microbatch_id, pair in enumerate(preprocessed)] + # Two optimizer steps of two micro-batches each: the id counts on, the step index follows the window. + assert forwarded == [ + (0, 0, False, [preprocessed[0]]), + (1, 0, False, [preprocessed[1]]), + (2, 1, False, [preprocessed[2]]), + (3, 1, False, [preprocessed[3]]), + ] assert output_pairs == preprocessed assert actor.global_step == 2 @@ -116,5 +129,17 @@ def test_without_the_hook_the_converted_pairs_train(): output_pairs = _load_train_core()(actor, rollout_id=0, rollout_data={"train_data": pairs}, external_data={}) - assert forwarded == [(index, [pair]) for index, pair in enumerate(pairs)] + assert forwarded == [(index, index // 2, False, [pair]) for index, pair in enumerate(pairs)] assert output_pairs == pairs + + +def test_the_recompute_passes_the_numbers_of_the_training_forwards_of_windows_1_on(): + pairs = [{"sample_index": index} for index in range(4)] + forwarded = [] + actor = _actor(None, lambda ctx, train_pairs: None, forwarded, diffusion_recompute_old_log_prob=True) + + _load_train_core()(actor, rollout_id=0, rollout_data={"train_data": pairs}, external_data={}) + + recompute = [(2, 1, True, [pairs[2]]), (3, 1, True, [pairs[3]])] + training = [(index, index // 2, False, [pair]) for index, pair in enumerate(pairs)] + assert forwarded == recompute + training From f7c559706b33e4853ee16f464e66e0f24c28e6af Mon Sep 17 00:00:00 2001 From: rockdu Date: Tue, 10 Nov 2026 13:09:42 -0800 Subject: [PATCH 22/33] refactor(fsdp): hand the train-output list to the hooks as an argument The DMD2 critic formula appended its scoring inputs to a list on the context and the train-output hook read them back: a hook-to-hook channel invisible in the call graph. The trunk now owns one list per train call and passes it to the formulas and to the train-output hook. --- docs/user-guide/customization.md | 16 +++--- miles/backends/fsdp_utils/actor.py | 7 ++- .../backends/fsdp_utils/loss_hub/__init__.py | 11 +++-- miles/backends/fsdp_utils/loss_hub/dmd2.py | 11 +++-- .../backends/fsdp_utils/loss_hub/flow_grpo.py | 1 + miles/backends/fsdp_utils/loss_hub/nft.py | 1 + miles/backends/fsdp_utils/loss_hub/sft.py | 1 + miles/backends/fsdp_utils/loss_hub/types.py | 2 - miles/utils/arguments.py | 4 +- .../fsdp_utils/_reference_models_worker.py | 2 + .../backends/fsdp_utils/test_h3_streams.py | 2 + .../backends/fsdp_utils/test_loss_hub_dmd2.py | 49 ++++++++++++------- .../backends/fsdp_utils/test_loss_hub_nft.py | 1 + .../fsdp_utils/test_loss_hub_selection.py | 2 +- .../backends/fsdp_utils/test_loss_hub_sft.py | 15 +++++- .../fsdp_utils/test_reference_models.py | 33 ++++++++++++- .../fsdp_utils/test_train_input_hook.py | 17 +++++-- 17 files changed, 129 insertions(+), 46 deletions(-) diff --git a/docs/user-guide/customization.md b/docs/user-guide/customization.md index 1c0900518..3a5f30314 100644 --- a/docs/user-guide/customization.md +++ b/docs/user-guide/customization.md @@ -294,11 +294,15 @@ counts from 0; the old-log-prob recompute of windows 1.. passes their training f ### `--custom-loss-function-path` ```python -def loss_formula(ctx, batch, prepared, *, new_pred, old_pred, ref_pred, metrics, **kwargs): +def loss_formula( + ctx, batch, prepared, *, new_pred, old_pred, ref_pred, metrics, optim_step_idx, train_output_inputs, **kwargs +): ... ``` -Read only under `--loss-type custom_loss`. `new_pred`, `old_pred` and `ref_pred` are keyed by the same stream +Read only under `--loss-type custom_loss`. `optim_step_idx` is the micro-batch's optimizer step within the rollout; +`train_output_inputs` is the list the formula may fill for the train-output hook, empty at the start of each train +call. `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`. @@ -319,16 +323,14 @@ and the train-output hook see the returned pairs. ### `--custom-train-output-function-path` ```python -def train_output(ctx, train_pairs) -> Any: +def train_output(ctx, train_pairs, train_output_inputs) -> Any: ... ``` Read only under `--loss-type custom_loss`. Runs without grad after this trainer group's train steps on a -rollout. Every trainer group that +rollout, with the list the loss formula filled. 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 -starts empty on each train call. +train pairs) as `ctx.external_data[]`. ### `--sde-step-backend-path` diff --git a/miles/backends/fsdp_utils/actor.py b/miles/backends/fsdp_utils/actor.py index 7d0cdf0cb..d296992a4 100644 --- a/miles/backends/fsdp_utils/actor.py +++ b/miles/backends/fsdp_utils/actor.py @@ -370,6 +370,7 @@ def _train_core(self, rollout_id: int, rollout_data, external_data: dict[str, An ) if self.loss_hooks.train_input is not None: train_pairs = self.loss_hooks.train_input(loss_ctx, train_pairs) + train_output_inputs: list = [] # one list per train call num_pairs = len(train_pairs) @@ -419,6 +420,7 @@ def _train_core(self, rollout_id: int, rollout_data, external_data: dict[str, An train_pairs[pair_lo:pair_hi], microbatch_id=microbatch_id, optim_step_idx=optim_step_idx, + train_output_inputs=train_output_inputs, metrics=unused_metrics, pad_to_len=legacy_pad_to_len, write_old_log_prob=True, @@ -453,6 +455,7 @@ def _train_core(self, rollout_id: int, rollout_data, external_data: dict[str, An chunk, microbatch_id=microbatch_id, optim_step_idx=optim_step_idx, + train_output_inputs=train_output_inputs, metrics=metrics, pad_to_len=legacy_pad_to_len, old_log_prob_from_new=old_log_prob_from_new, @@ -489,7 +492,7 @@ def _train_core(self, rollout_id: int, rollout_data, external_data: dict[str, An if self.loss_hooks.train_output is not None: with torch.no_grad(): - return self.loss_hooks.train_output(loss_ctx, train_pairs) + return self.loss_hooks.train_output(loss_ctx, train_pairs, train_output_inputs) 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 @@ -512,6 +515,7 @@ def _forward_train_pair_batch( *, microbatch_id: int, optim_step_idx: int, + train_output_inputs: list, metrics: MetricBuffer, pad_to_len: int | None = None, write_old_log_prob: bool = False, @@ -581,6 +585,7 @@ def _compute_noise_pred(model) -> dict[str, torch.Tensor]: ref_pred=ref_pred, metrics=metrics, optim_step_idx=optim_step_idx, + train_output_inputs=train_output_inputs, write_old_log_prob=write_old_log_prob, old_log_prob_from_new=old_log_prob_from_new, ) diff --git a/miles/backends/fsdp_utils/loss_hub/__init__.py b/miles/backends/fsdp_utils/loss_hub/__init__.py index bbe51d5e5..651570b37 100644 --- a/miles/backends/fsdp_utils/loss_hub/__init__.py +++ b/miles/backends/fsdp_utils/loss_hub/__init__.py @@ -30,15 +30,18 @@ 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(ctx, batch, *, microbatch_id, optim_step_idx, pad_to_len=None)`` builds a micro-batch's DiT inputs, + ``formula(ctx, batch, prepared, *, new_pred, old_pred, ref_pred, metrics, optim_step_idx, train_output_inputs, + ...)`` turns the predictions into its loss, ``train_input`` preprocesses the rank's train pairs before + micro-batching, and ``train_output(ctx, train_pairs, train_output_inputs)`` runs after the train steps and hands + its return value to the groups that train later; ``train_output_inputs`` is the list the formulas filled during + this train call. """ prepare: Callable[..., PreparedBatch] formula: Callable[..., torch.Tensor | None] train_input: Callable[[DiffusionLossContext, list], list] | None = None - train_output: Callable[[DiffusionLossContext, list], Any] | None = None + train_output: Callable[[DiffusionLossContext, list, list], Any] | None = None LOSS_HOOKS: dict[tuple[str, str], LossHooks] = { diff --git a/miles/backends/fsdp_utils/loss_hub/dmd2.py b/miles/backends/fsdp_utils/loss_hub/dmd2.py index 06257db27..2388cd17f 100644 --- a/miles/backends/fsdp_utils/loss_hub/dmd2.py +++ b/miles/backends/fsdp_utils/loss_hub/dmd2.py @@ -60,6 +60,7 @@ def critic_loss_formula( ref_pred: dict[str, torch.Tensor] | None, metrics: MetricBuffer, optim_step_idx: int, + train_output_inputs: list, write_old_log_prob: bool = False, old_log_prob_from_new: bool = False, ) -> torch.Tensor: @@ -71,7 +72,7 @@ def critic_loss_formula( sigmas = prepared.extras["sigmas"]["visual"].view(len(batch), *([1] * (latents.ndim - 1))) if _is_scoring_step(ctx, optim_step_idx): x0_fake = latents - sigmas * new_pred["visual"].detach().float() - ctx.train_output_inputs.append( + train_output_inputs.append( (batch, prepared.component_name, latents, prepared.timesteps["visual"], sigmas, x0_fake) ) if ctx.args.dmd2_critic_loss_space == "x0": @@ -88,15 +89,18 @@ def critic_loss_formula( ref_pred=ref_pred, metrics=metrics, optim_step_idx=optim_step_idx, + train_output_inputs=train_output_inputs, write_old_log_prob=write_old_log_prob, old_log_prob_from_new=old_log_prob_from_new, ) -def score_last_step_samples(ctx: DiffusionLossContext, train_pairs: list[dict]) -> dict[int, dict]: +def score_last_step_samples( + ctx: DiffusionLossContext, train_pairs: list[dict], train_output_inputs: list +) -> dict[int, dict]: """The teacher's x0 at each scored sample's noisy input, next to the critic's x0 kept there, by sample.""" predictions = {} - for batch, component_name, latents, timesteps, sigmas, x0_fake in ctx.train_output_inputs: + for batch, component_name, latents, timesteps, sigmas, x0_fake in train_output_inputs: teacher = ctx.teacher_models[component_name] real_pred = _predict_velocity(ctx, teacher, batch, latents, timesteps, ctx.args.dmd2_teacher_guidance_scale) for pair, x0_real, fake in zip(batch, latents - sigmas * real_pred, x0_fake, strict=True): @@ -229,6 +233,7 @@ def dmd2_loss_formula( ref_pred: dict[str, torch.Tensor] | None, metrics: MetricBuffer, optim_step_idx: int, + train_output_inputs: list, write_old_log_prob: bool = False, old_log_prob_from_new: bool = False, ) -> torch.Tensor: diff --git a/miles/backends/fsdp_utils/loss_hub/flow_grpo.py b/miles/backends/fsdp_utils/loss_hub/flow_grpo.py index 050a6e431..147208910 100644 --- a/miles/backends/fsdp_utils/loss_hub/flow_grpo.py +++ b/miles/backends/fsdp_utils/loss_hub/flow_grpo.py @@ -121,6 +121,7 @@ def flow_grpo_loss_formula( ref_pred: dict[str, torch.Tensor] | None, metrics: MetricBuffer, optim_step_idx: int, + train_output_inputs: list, write_old_log_prob: bool = False, old_log_prob_from_new: bool = False, ) -> torch.Tensor | None: diff --git a/miles/backends/fsdp_utils/loss_hub/nft.py b/miles/backends/fsdp_utils/loss_hub/nft.py index 306e9c84c..88765cd94 100644 --- a/miles/backends/fsdp_utils/loss_hub/nft.py +++ b/miles/backends/fsdp_utils/loss_hub/nft.py @@ -115,6 +115,7 @@ def nft_loss_formula( ref_pred: dict[str, torch.Tensor] | None, metrics: MetricBuffer, optim_step_idx: int, + train_output_inputs: list, write_old_log_prob: bool = False, old_log_prob_from_new: bool = False, ) -> torch.Tensor: diff --git a/miles/backends/fsdp_utils/loss_hub/sft.py b/miles/backends/fsdp_utils/loss_hub/sft.py index bcab5c070..df1ca25a3 100644 --- a/miles/backends/fsdp_utils/loss_hub/sft.py +++ b/miles/backends/fsdp_utils/loss_hub/sft.py @@ -129,6 +129,7 @@ def sft_loss_formula( ref_pred: dict[str, torch.Tensor] | None, metrics: MetricBuffer, optim_step_idx: int, + train_output_inputs: list, write_old_log_prob: bool = False, old_log_prob_from_new: bool = False, ) -> torch.Tensor: diff --git a/miles/backends/fsdp_utils/loss_hub/types.py b/miles/backends/fsdp_utils/loss_hub/types.py index f25c62dc5..f88068717 100644 --- a/miles/backends/fsdp_utils/loss_hub/types.py +++ b/miles/backends/fsdp_utils/loss_hub/types.py @@ -25,8 +25,6 @@ class DiffusionLossContext: reference_models: dict[str, torch.nn.Module] = field(default_factory=dict) teacher_models: dict[str, torch.nn.Module] = field(default_factory=dict) external_data: dict[str, Any] = field(default_factory=dict) - # Filled by loss hooks during one train call and read by the train-output hook. - train_output_inputs: list[Any] = field(default_factory=list) @dataclass(frozen=True) diff --git a/miles/utils/arguments.py b/miles/utils/arguments.py index 712c08aa3..3870cdec3 100644 --- a/miles/utils/arguments.py +++ b/miles/utils/arguments.py @@ -991,8 +991,8 @@ def add_algo_arguments(parser): type=str, default=None, 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 " + "Dotted path to `fn(ctx, train_pairs, train_output_inputs) -> Any`, run without grad after the " + "train steps of a rollout with the list the loss formula filled. Its return value reaches the paired rank of every trainer group that trains " "later on the same rollout as `ctx.external_data[]`. --loss-type custom_loss only." ), ) diff --git a/tests/fast-gpu/backends/fsdp_utils/_reference_models_worker.py b/tests/fast-gpu/backends/fsdp_utils/_reference_models_worker.py index 2b33278fa..6fc39746d 100644 --- a/tests/fast-gpu/backends/fsdp_utils/_reference_models_worker.py +++ b/tests/fast-gpu/backends/fsdp_utils/_reference_models_worker.py @@ -98,6 +98,7 @@ def check_roles(mesh, adapter_paths, reference_has_adapter, cpu_offload): [], microbatch_id=0, optim_step_idx=0, + train_output_inputs=[], metrics=None, ).backward() expected_actor_output = oracle(inputs) @@ -129,6 +130,7 @@ def check_roles(mesh, adapter_paths, reference_has_adapter, cpu_offload): [], microbatch_id=0, optim_step_idx=0, + train_output_inputs=[], metrics=None, ).backward() expected_actor_output = oracle(inputs) diff --git a/tests/fast/backends/fsdp_utils/test_h3_streams.py b/tests/fast/backends/fsdp_utils/test_h3_streams.py index 94c53c24a..0f56dd4b0 100644 --- a/tests/fast/backends/fsdp_utils/test_h3_streams.py +++ b/tests/fast/backends/fsdp_utils/test_h3_streams.py @@ -133,6 +133,7 @@ def test_t2va_prediction_matches_the_sft_target_and_skips_padding_rows(): ref_pred=None, metrics=metrics, optim_step_idx=0, + train_output_inputs=[], ) assert torch.isfinite(loss) and loss.item() > 0 @@ -441,6 +442,7 @@ def test_real_tiny_diffusers_h3_joint_sft_forward_and_backward(forward_dtype): ref_pred=None, metrics=metrics, optim_step_idx=0, + train_output_inputs=[], ) assert torch.isfinite(loss) and loss.item() > 0 assert prepared.extras["target"]["visual"].dtype == torch.float32 diff --git a/tests/fast/backends/fsdp_utils/test_loss_hub_dmd2.py b/tests/fast/backends/fsdp_utils/test_loss_hub_dmd2.py index c440dc385..c24e6d01a 100644 --- a/tests/fast/backends/fsdp_utils/test_loss_hub_dmd2.py +++ b/tests/fast/backends/fsdp_utils/test_loss_hub_dmd2.py @@ -136,7 +136,7 @@ def _ctx(teacher_guidance_scale=3.0, critic_scale=1.0, teacher_scale=1.0): ) -def _critic_step(ctx, pairs, optim_step_idx, metrics=None): +def _critic_step(ctx, pairs, optim_step_idx, train_output_inputs, metrics=None): """One critic optimizer step as _train_core runs it: prepare, the critic's training forward, the loss hook.""" steps = [] for start in range(0, len(pairs), ctx.args.micro_batch_size): @@ -165,6 +165,7 @@ def _critic_step(ctx, pairs, optim_step_idx, metrics=None): ref_pred=None, metrics=metrics or _Metrics(), optim_step_idx=optim_step_idx, + train_output_inputs=train_output_inputs, ) steps.append((batch, prepared, new_pred, loss)) return steps @@ -240,7 +241,7 @@ def test_critic_loss_is_the_sft_loss(): ctx = _ctx() metrics = _Metrics() sft_metrics = _Metrics() - for batch, prepared, new_pred, loss in _critic_step(ctx, _pairs(3), optim_step_idx, metrics): + for batch, prepared, new_pred, loss in _critic_step(ctx, _pairs(3), optim_step_idx, [], metrics): sft_loss = sft_loss_formula( ctx, batch, @@ -250,6 +251,7 @@ def test_critic_loss_is_the_sft_loss(): ref_pred=None, metrics=sft_metrics, optim_step_idx=optim_step_idx, + train_output_inputs=[], ) assert torch.equal(loss, sft_loss) assert metrics.seen == sft_metrics.seen @@ -260,7 +262,7 @@ def test_x0_critic_loss_weights_the_velocity_mse(): ctx = _ctx() ctx.models["transformer"] = _NoisyInputVelocity() ctx.args.dmd2_critic_loss_space = "x0" - for batch, prepared, new_pred, loss in _critic_step(ctx, _pairs(3), optim_step_idx): + for batch, prepared, new_pred, loss in _critic_step(ctx, _pairs(3), optim_step_idx, []): x_s = prepared.latents["visual"] sigma = prepared.extras["sigmas"]["visual"].view(-1, 1, 1, 1) x0 = torch.stack([pair["x0"] for pair in batch]) @@ -274,12 +276,14 @@ def test_only_the_last_step_keeps_scoring_inputs(): ctx = _ctx() pairs = _pairs(9) + inputs = [] for optim_step_idx in range(CRITIC_STEPS - 1): - _critic_step(ctx, pairs[optim_step_idx * 3 : optim_step_idx * 3 + 3], optim_step_idx) - assert ctx.train_output_inputs == [] + _critic_step(ctx, pairs[optim_step_idx * 3 : optim_step_idx * 3 + 3], optim_step_idx, inputs) + assert inputs == [] - _critic_step(ctx, pairs[6:], CRITIC_STEPS - 1) - scores = dmd2.score_last_step_samples(ctx, pairs) + _critic_step(ctx, pairs[6:], CRITIC_STEPS - 1, inputs) + assert len(inputs) == 2 # one entry per micro-batch of the last step + scores = dmd2.score_last_step_samples(ctx, pairs, inputs) assert list(scores) == [106, 107, 108] @@ -289,8 +293,9 @@ def test_scores_match_separate_forwards_at_the_kept_input(): ctx.models["transformer"] = _NoisyInputVelocity() pairs = _pairs(5) - steps = _critic_step(ctx, pairs, CRITIC_STEPS - 1) - scores = dmd2.score_last_step_samples(ctx, pairs) + inputs = [] + steps = _critic_step(ctx, pairs, CRITIC_STEPS - 1, inputs) + scores = dmd2.score_last_step_samples(ctx, pairs, inputs) assert list(scores) == [100, 101, 102, 103, 104] for batch, prepared, _, _ in steps: @@ -308,8 +313,9 @@ def test_teacher_runs_cfg_and_the_critic_runs_unguided(): ctx = _ctx(teacher_guidance_scale=3.0, teacher_scale=1.0, critic_scale=2.0) pairs = _pairs(2) - [(_, prepared, _, _)] = _critic_step(ctx, pairs, CRITIC_STEPS - 1) - scores = dmd2.score_last_step_samples(ctx, pairs) + inputs = [] + [(_, prepared, _, _)] = _critic_step(ctx, pairs, CRITIC_STEPS - 1, inputs) + scores = dmd2.score_last_step_samples(ctx, pairs, inputs) x_s = prepared.latents["visual"] sigma = prepared.extras["sigmas"]["visual"].view(-1, 1, 1, 1) @@ -323,22 +329,25 @@ def test_teacher_runs_cfg_and_the_critic_runs_unguided(): def test_teacher_cfg_needs_the_rollout_negative_cond(): ctx = _ctx(teacher_guidance_scale=3.0) - _critic_step(ctx, _pairs(2, with_neg=False), CRITIC_STEPS - 1) + inputs = [] + _critic_step(ctx, _pairs(2, with_neg=False), CRITIC_STEPS - 1, inputs) with pytest.raises(ValueError, match="needs the rollout's negative cond"): - dmd2.score_last_step_samples(ctx, _pairs(2, with_neg=False)) + dmd2.score_last_step_samples(ctx, _pairs(2, with_neg=False), inputs) # Unguided, the teacher reads only the positive cond. ctx = _ctx(teacher_guidance_scale=1.0) - _critic_step(ctx, _pairs(2, with_neg=False), CRITIC_STEPS - 1) - dmd2.score_last_step_samples(ctx, _pairs(2, with_neg=False)) + inputs = [] + _critic_step(ctx, _pairs(2, with_neg=False), CRITIC_STEPS - 1, inputs) + dmd2.score_last_step_samples(ctx, _pairs(2, with_neg=False), inputs) def test_scoring_reshards_the_teacher(monkeypatch): resharded = [] monkeypatch.setattr(dmd2, "reshard_model", resharded.append) ctx = _ctx() - _critic_step(ctx, _pairs(2), CRITIC_STEPS - 1) + inputs = [] + _critic_step(ctx, _pairs(2), CRITIC_STEPS - 1, inputs) - dmd2.score_last_step_samples(ctx, _pairs(2)) + dmd2.score_last_step_samples(ctx, _pairs(2), inputs) assert resharded == [ctx.teacher_models["transformer"]] @@ -349,11 +358,12 @@ def test_actor_keeps_the_critic_last_step_pairs(): schedule = build_microbatch_schedule( num_pairs_per_optim_step=3, num_optim_steps_per_rollout=CRITIC_STEPS, micro_batch_size=3 ) + inputs = [] for optim_step_idx, [(pair_lo, pair_hi)] in enumerate(schedule): - _critic_step(ctx, pairs[pair_lo:pair_hi], optim_step_idx) + _critic_step(ctx, pairs[pair_lo:pair_hi], optim_step_idx, inputs) actor_ctx = _ctx() - actor_ctx.external_data["critic"] = dmd2.score_last_step_samples(ctx, pairs) + actor_ctx.external_data["critic"] = dmd2.score_last_step_samples(ctx, pairs, inputs) assert dmd2.select_scored_pairs(actor_ctx, pairs) == pairs[6:] @@ -401,6 +411,7 @@ def _loss(ctx, pairs, x0): ref_pred=None, metrics=metrics, optim_step_idx=0, + train_output_inputs=[], ), metrics, ) 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 e38832bb8..c711e54a6 100644 --- a/tests/fast/backends/fsdp_utils/test_loss_hub_nft.py +++ b/tests/fast/backends/fsdp_utils/test_loss_hub_nft.py @@ -90,6 +90,7 @@ def loss(kl_beta): ref_pred={"visual": new_pred["visual"] - 1.0}, metrics=metrics, optim_step_idx=0, + train_output_inputs=[], ) torch.testing.assert_close(loss(0.5) - loss(0.0), torch.tensor(0.5 * 2)) 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 5d51f4079..0f1019464 100644 --- a/tests/fast/backends/fsdp_utils/test_loss_hub_selection.py +++ b/tests/fast/backends/fsdp_utils/test_loss_hub_selection.py @@ -89,7 +89,7 @@ def formula(ctx, batch, prepared, **kwargs): def train_input(ctx, train_pairs): pass - def train_output(ctx, train_pairs): + def train_output(ctx, train_pairs, train_output_inputs): pass args = _custom_args( diff --git a/tests/fast/backends/fsdp_utils/test_loss_hub_sft.py b/tests/fast/backends/fsdp_utils/test_loss_hub_sft.py index 813ceb01c..68b8b8a01 100644 --- a/tests/fast/backends/fsdp_utils/test_loss_hub_sft.py +++ b/tests/fast/backends/fsdp_utils/test_loss_hub_sft.py @@ -255,6 +255,7 @@ def _loss(self, prediction_offset, metrics, log_loss_sigma_bucket=5): ref_pred=None, metrics=metrics, optim_step_idx=0, + train_output_inputs=[], ) def test_zero_loss_on_exact_velocity(self): @@ -360,6 +361,7 @@ def test_loss_averages_each_stream_over_its_own_size(self): ref_pred=None, metrics=metrics, optim_step_idx=0, + train_output_inputs=[], ) assert loss.item() == pytest.approx(10.0) loss.backward() @@ -381,7 +383,15 @@ def test_joint_metrics_split_by_stream_and_bucket_by_own_sigma(self): } metrics = _Metrics() sft_loss_formula( - ctx, batch, prepared, new_pred=predictions, old_pred=None, ref_pred=None, metrics=metrics, optim_step_idx=0 + ctx, + batch, + prepared, + new_pred=predictions, + old_pred=None, + ref_pred=None, + metrics=metrics, + optim_step_idx=0, + train_output_inputs=[], ) assert metrics.seen["loss"] == (10.0, 2) assert metrics.seen["loss_visual"] == (2.0, 2) @@ -412,6 +422,7 @@ def test_a_stream_the_config_does_not_predict_adds_no_loss(self): ref_pred=None, metrics=_Metrics(), optim_step_idx=0, + train_output_inputs=[], ) assert loss.item() == pytest.approx(2.0) @@ -434,6 +445,7 @@ def test_a_stream_left_out_of_supervised_streams_adds_no_loss(self): ref_pred=None, metrics=metrics, optim_step_idx=0, + train_output_inputs=[], ) assert loss.item() == pytest.approx(2.0) # One supervised stream: its loss is the total, and only its own buckets appear. @@ -469,6 +481,7 @@ def test_rejects_misshaped_predictions(self): ref_pred=None, metrics=_Metrics(), optim_step_idx=0, + train_output_inputs=[], ) def test_rejects_different_stream_sets_in_one_microbatch(self): diff --git a/tests/fast/backends/fsdp_utils/test_reference_models.py b/tests/fast/backends/fsdp_utils/test_reference_models.py index 8d9674814..f57aaadfb 100644 --- a/tests/fast/backends/fsdp_utils/test_reference_models.py +++ b/tests/fast/backends/fsdp_utils/test_reference_models.py @@ -158,9 +158,14 @@ def make_actor_forward_harness( true_cfg_scale=None, ) + def prepare(ctx, batch, **kwargs): + observed["prepare_kwargs"] = kwargs + return prepared + def loss_formula(ctx, batch, prepared, *, new_pred, old_pred, ref_pred, **kwargs): predictions = {"new_pred": new_pred, "old_pred": old_pred, "ref_pred": ref_pred} observed.update({name: pred["visual"] for name, pred in predictions.items() if pred is not None}) + observed["formula_kwargs"] = kwargs return (new_pred["visual"] - ref_pred["visual"]).square().mean() harness = SimpleNamespace( @@ -171,7 +176,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, - loss_hooks=SimpleNamespace(prepare=lambda *args, **kwargs: prepared, formula=loss_formula), + loss_hooks=SimpleNamespace(prepare=prepare, formula=loss_formula), ) return harness, observed @@ -265,6 +270,7 @@ def test_loaded_reference_and_teacher_are_independent_and_frozen( [], microbatch_id=0, optim_step_idx=0, + train_output_inputs=[], metrics=None, ).backward() oracle_output = oracle(inputs) @@ -312,6 +318,7 @@ def test_lora_base_forward_restores_adapters_and_actor_gradients(tmp_path, unsha [], microbatch_id=0, optim_step_idx=0, + train_output_inputs=[], metrics=None, ).backward() oracle_output = oracle(inputs) @@ -373,6 +380,7 @@ def test_lora_base_reference_keeps_adapter_gradients_on_fsdp_shards(): [], microbatch_id=0, optim_step_idx=0, + train_output_inputs=[], metrics=None, ).backward() for name, parameter in adapter_parameters.items(): @@ -417,6 +425,7 @@ def test_nft_gets_ema_as_old_and_lora_base_as_kl_reference(tmp_path, unsharded_m [], microbatch_id=0, optim_step_idx=0, + train_output_inputs=[], metrics=None, ) torch.testing.assert_close(observed["new_pred"], expected_new) @@ -480,3 +489,25 @@ def gather_object(*, obj, object_gather_list, **kwargs): namespace[method.name](harness, [("block.proj.lora_A.weight", torch.ones(2, 3))], "transformer") assert len(sent) == 1 assert sent[0]["lora_rank"] == 2 and sent[0]["lora_alpha"] == 4 + + +def test_the_trunk_hands_the_hooks_their_own_counters_and_the_one_list(): + model = torch.nn.Linear(3, 3) + harness, observed = make_actor_forward_harness( + {"block": model}, {"block": model}, "block", torch.ones(2, 3), "ref" + ) + train_output_inputs = [] + + load_actor_forward_method()( + harness, + None, + [], + microbatch_id=7, + optim_step_idx=2, + train_output_inputs=train_output_inputs, + metrics=None, + ) + + assert observed["prepare_kwargs"] == {"microbatch_id": 7, "optim_step_idx": 2, "pad_to_len": None} + assert observed["formula_kwargs"]["optim_step_idx"] == 2 + assert observed["formula_kwargs"]["train_output_inputs"] is train_output_inputs 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 11e119410..ccb573cc9 100644 --- a/tests/fast/backends/fsdp_utils/test_train_input_hook.py +++ b/tests/fast/backends/fsdp_utils/test_train_input_hook.py @@ -3,7 +3,7 @@ train pairs (the converted rollout output) + ctx (external_data from earlier groups) --train-input hook (filter / reorder / rewrite)--> preprocessed pairs preprocessed pairs --> micro-batch schedule --> training forwards, in order - preprocessed pairs --> train-output hook (the same ctx) + preprocessed pairs --> train-output hook (the same ctx, the list the forwards filled) no hook --> the converted train pairs, as before The trunk numbers each forward: ``microbatch_id`` counts the rollout's micro-batches, ``optim_step_idx`` is the @@ -55,7 +55,9 @@ def _load_train_core(): def _actor(train_input, train_output, forwarded, **args): + lists = [] # the train_output_inputs object each forward received return SimpleNamespace( + lists=lists, models={}, reference_models={}, teacher_models={}, @@ -80,6 +82,8 @@ def _actor(train_input, train_output, forwarded, **args): forwarded.append( (kwargs["microbatch_id"], kwargs["optim_step_idx"], kwargs.get("write_old_log_prob", False), chunk) ), + kwargs["train_output_inputs"].append(kwargs["microbatch_id"]), + lists.append(kwargs["train_output_inputs"]), ), _log_metrics=lambda rollout_id, metrics, step: None, ) @@ -103,8 +107,8 @@ def train_input(ctx, train_pairs): ] forwarded = [] - actor = _actor(train_input, lambda ctx, train_pairs: (ctx, train_pairs), forwarded) - ctx, output_pairs = _load_train_core()( + actor = _actor(train_input, lambda ctx, train_pairs, inputs: (ctx, train_pairs, inputs), forwarded) + ctx, output_pairs, train_output_inputs = _load_train_core()( actor, rollout_id=3, rollout_data={"train_data": pairs}, external_data={"critic": scores} ) @@ -119,13 +123,16 @@ def train_input(ctx, train_pairs): (3, 1, False, [preprocessed[3]]), ] assert output_pairs == preprocessed + # Every forward appended to the one list the train-output hook received. + assert train_output_inputs == [0, 1, 2, 3] + assert all(received is train_output_inputs for received in actor.lists) assert actor.global_step == 2 def test_without_the_hook_the_converted_pairs_train(): pairs = [{"sample_index": index} for index in range(4)] forwarded = [] - actor = _actor(None, lambda ctx, train_pairs: train_pairs, forwarded) + actor = _actor(None, lambda ctx, train_pairs, inputs: train_pairs, forwarded) output_pairs = _load_train_core()(actor, rollout_id=0, rollout_data={"train_data": pairs}, external_data={}) @@ -136,7 +143,7 @@ def test_without_the_hook_the_converted_pairs_train(): def test_the_recompute_passes_the_numbers_of_the_training_forwards_of_windows_1_on(): pairs = [{"sample_index": index} for index in range(4)] forwarded = [] - actor = _actor(None, lambda ctx, train_pairs: None, forwarded, diffusion_recompute_old_log_prob=True) + actor = _actor(None, lambda ctx, train_pairs, inputs: None, forwarded, diffusion_recompute_old_log_prob=True) _load_train_core()(actor, rollout_id=0, rollout_data={"train_data": pairs}, external_data={}) From 60acc023dab78c539b708879d0e2a477f3f916a5 Mon Sep 17 00:00:00 2001 From: rockdu Date: Tue, 10 Nov 2026 13:09:42 -0800 Subject: [PATCH 23/33] refactor(fsdp): freeze DiffusionLossContext Nothing writes the context after construction any more: it is the rollout-level, read-only view the hooks share. eq=False keeps identity comparison; a synthesized hash would fail on the dict fields. --- miles/backends/fsdp_utils/loss_hub/types.py | 7 +++++-- .../backends/fsdp_utils/test_loss_hub_dmd2.py | 21 +++++++++---------- .../backends/fsdp_utils/test_loss_hub_sft.py | 7 +++++++ 3 files changed, 22 insertions(+), 13 deletions(-) diff --git a/miles/backends/fsdp_utils/loss_hub/types.py b/miles/backends/fsdp_utils/loss_hub/types.py index f88068717..129d08cad 100644 --- a/miles/backends/fsdp_utils/loss_hub/types.py +++ b/miles/backends/fsdp_utils/loss_hub/types.py @@ -10,9 +10,12 @@ import torch.nn as nn -@dataclass +@dataclass(frozen=True, eq=False) class DiffusionLossContext: - """Train-side handles for prepare and loss hooks.""" + """Rollout-level, read-only handles for the loss hooks; what changes per micro-batch travels as arguments. + + Compared by identity: nothing hashes a context, and a synthesized hash would fail on the dict fields. + """ models: dict[str, torch.nn.Module] train_pipeline_config: Any diff --git a/tests/fast/backends/fsdp_utils/test_loss_hub_dmd2.py b/tests/fast/backends/fsdp_utils/test_loss_hub_dmd2.py index c24e6d01a..c05447b30 100644 --- a/tests/fast/backends/fsdp_utils/test_loss_hub_dmd2.py +++ b/tests/fast/backends/fsdp_utils/test_loss_hub_dmd2.py @@ -48,6 +48,7 @@ register_cpu_ci(est_time=10, suite="stage-a-cpu", labels=[]) +import dataclasses from argparse import Namespace import pytest @@ -450,7 +451,7 @@ def test_surrogate_gradient_matches_the_reference(): pairs = _generator_pairs(2) x0 = torch.randn(2, *LATENT_SHAPE, requires_grad=True) x0_real, x0_fake = torch.randn(2, *LATENT_SHAPE), torch.randn(2, *LATENT_SHAPE) - ctx.external_data = {"critic": _scores(pairs, x0_real, x0_fake)} + ctx = dataclasses.replace(ctx, external_data={"critic": _scores(pairs, x0_real, x0_fake)}) loss_sum, _ = _loss(ctx, pairs, x0) (loss_sum / len(pairs)).backward() @@ -470,7 +471,7 @@ def test_critic_matching_the_teacher_gives_no_gradient(): pairs = _generator_pairs(2) x0 = torch.randn(2, *LATENT_SHAPE, requires_grad=True) x0_pred = torch.randn(2, *LATENT_SHAPE) - ctx.external_data = {"critic": _scores(pairs, x0_pred, x0_pred)} + ctx = dataclasses.replace(ctx, external_data={"critic": _scores(pairs, x0_pred, x0_pred)}) loss_sum, metrics = _loss(ctx, pairs, x0) loss_sum.backward() @@ -496,13 +497,8 @@ def posterior_mean(mu, x_s, a, b): x0 = student_mu + torch.randn(2, *LATENT_SHAPE, generator=generator) a, b = 0.5, 0.5 x_s = a * x0.detach() + b * torch.randn(x0.shape, generator=generator) - ctx.external_data = { - "critic": _scores( - pairs, - posterior_mean(teacher_mu, x_s, a, b), - posterior_mean(float(student_mu), x_s, a, b), - ) - } + scores = _scores(pairs, posterior_mean(teacher_mu, x_s, a, b), posterior_mean(float(student_mu), x_s, a, b)) + ctx = dataclasses.replace(ctx, external_data={"critic": scores}) loss_sum, _ = _loss(ctx, pairs, x0) (loss_sum / len(pairs)).backward() optimizer.step() @@ -516,7 +512,7 @@ def test_trainer_and_rollout_x0_diff_is_recorded(): ctx = _ctx() pairs = _generator_pairs(2) x0 = torch.stack([pair["x0"] for pair in pairs]) + 0.25 - ctx.external_data = {"critic": _scores(pairs, x0, x0)} + ctx = dataclasses.replace(ctx, external_data={"critic": _scores(pairs, x0, x0)}) _, metrics = _loss(ctx, pairs, x0) @@ -530,7 +526,10 @@ def test_health_metrics_are_recorded_overall_and_per_step(): pairs = _generator_pairs(2) # Pair n stopped at step n: x0 = 0.5 + n against a teacher x0 of 0 and a critic x0 of 0.25. x0 = torch.stack([pair["x0"] for pair in pairs]) + torch.tensor([0.5, 1.5]).view(2, 1, 1, 1) - ctx.external_data = {"critic": _scores(pairs, torch.zeros(2, *LATENT_SHAPE), torch.full((2, *LATENT_SHAPE), 0.25))} + ctx = dataclasses.replace( + ctx, + external_data={"critic": _scores(pairs, torch.zeros(2, *LATENT_SHAPE), torch.full((2, *LATENT_SHAPE), 0.25))}, + ) _, metrics = _loss(ctx, pairs, x0) diff --git a/tests/fast/backends/fsdp_utils/test_loss_hub_sft.py b/tests/fast/backends/fsdp_utils/test_loss_hub_sft.py index 68b8b8a01..bd63f01d2 100644 --- a/tests/fast/backends/fsdp_utils/test_loss_hub_sft.py +++ b/tests/fast/backends/fsdp_utils/test_loss_hub_sft.py @@ -36,6 +36,7 @@ register_cpu_ci(est_time=30, suite="stage-a-cpu", labels=[]) +import dataclasses from argparse import Namespace import pytest @@ -118,6 +119,12 @@ def emit_mean(self, key, *, total, count): self.seen[key] = (prev_total + float(total), prev_count + count) +def test_the_context_is_read_only(): + ctx = _ctx({"transformer": nn.Identity()}) + with pytest.raises(dataclasses.FrozenInstanceError): + ctx.rollout_id = 4 + + class TestPrepareSftBatch: def test_corruption_and_target_identity(self): torch.manual_seed(0) From 827b527d3d230fc63aadb4ee64629ff16867666f Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Wed, 11 Nov 2026 05:26:38 +0000 Subject: [PATCH 24/33] refactor(fsdp): run the DMD2 teacher forward in the actor, requested by the critic's prepare hook --- docs/fsdp_model_roles.md | 5 +- docs/user-guide/cli-reference.md | 2 +- docs/user-guide/customization.md | 17 +- miles/backends/fsdp_utils/actor.py | 33 +++- miles/backends/fsdp_utils/loss_hub/dmd2.py | 104 +++-------- .../backends/fsdp_utils/loss_hub/flow_grpo.py | 1 + miles/backends/fsdp_utils/loss_hub/nft.py | 1 + miles/backends/fsdp_utils/loss_hub/sft.py | 1 + miles/backends/fsdp_utils/loss_hub/types.py | 3 +- .../backends/fsdp_utils/test_loss_hub_dmd2.py | 175 ++++++++++++------ .../fsdp_utils/test_reference_models.py | 107 ++++++++++- .../fsdp_utils/test_train_input_hook.py | 1 - tests/fast/utils/test_reference_arguments.py | 2 +- 13 files changed, 296 insertions(+), 156 deletions(-) diff --git a/docs/fsdp_model_roles.md b/docs/fsdp_model_roles.md index 684039068..2e07d85c9 100644 --- a/docs/fsdp_model_roles.md +++ b/docs/fsdp_model_roles.md @@ -37,8 +37,9 @@ 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 only a custom hook reads it, from `ctx.teacher_models`, -and teacher inference should run inside `torch.no_grad()`. +scores the student's samples with it. The actor runs it like the reference: on a micro-batch whose +prepare hook sets `PreparedBatch.teacher_guidance_scale`, the teacher's no-grad forward at that CFG +scale runs before the training forward, and the loss formula receives it as `teacher_pred`. 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 90464a587..73c950c6a 100644 --- a/docs/user-guide/cli-reference.md +++ b/docs/user-guide/cli-reference.md @@ -273,7 +273,7 @@ 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, offered to the hooks as `ctx.teacher_models`; `--loss-type dmd2` scores the student's samples with it. | +| `--teacher-load` | str | – | HF pipeline checkpoint of a frozen teacher model; the actor runs it without grad on the micro-batches whose prepare hook sets `PreparedBatch.teacher_guidance_scale`, and `--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 | – | `custom_loss` only: builds DiT inputs. | diff --git a/docs/user-guide/customization.md b/docs/user-guide/customization.md index 3a5f30314..09e7465f9 100644 --- a/docs/user-guide/customization.md +++ b/docs/user-guide/customization.md @@ -248,9 +248,9 @@ flags (`--custom-prepare-train-batch-path`, `--custom-loss-function-path`, 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): +On its last step its prepare hook also asks for the teacher at the same noisy inputs, and its loss +formula keeps the critic's x0 from that step's forward, before the update, next to the teacher's; after +training its train-output hook hands them 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 @@ -289,13 +289,16 @@ counts from 0; the old-log-prob recompute of windows 1.. passes their training f `optim_step_idx` is its optimizer step; the built-in hooks seed their noise from `microbatch_id`. `PreparedBatch.latents`, `timesteps` and `timesteps_for_model` are keyed by latent stream name: `"visual"`, plus e.g. -`"audio"` for joint audio-video models. +`"audio"` for joint audio-video models. `PreparedBatch.teacher_guidance_scale` asks the trunk to run the frozen +teacher (`--teacher-load`) without grad on this micro-batch at that CFG scale, over `neg_cond` / `joint_cond`, before +the training forward; the formula receives it as `teacher_pred`. ### `--custom-loss-function-path` ```python def loss_formula( - ctx, batch, prepared, *, new_pred, old_pred, ref_pred, metrics, optim_step_idx, train_output_inputs, **kwargs + ctx, batch, prepared, *, new_pred, old_pred, ref_pred, teacher_pred, metrics, optim_step_idx, + train_output_inputs, **kwargs ): ... ``` @@ -304,7 +307,9 @@ Read only under `--loss-type custom_loss`. `optim_step_idx` is the micro-batch's `train_output_inputs` is the list the formula may fill for the train-output hook, empty at the start of each train call. `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`. +only under `--loss-type nft`; `ref_pred` is `None` with `--ref-mode none`. `teacher_pred` is the frozen teacher's +no-grad prediction at `prepared.teacher_guidance_scale`, which the trunk runs before the training forward when the +prepare hook sets that scale, else `None`. ### `--custom-train-input-postprocess-path` diff --git a/miles/backends/fsdp_utils/actor.py b/miles/backends/fsdp_utils/actor.py index d296992a4..de10e8ad9 100644 --- a/miles/backends/fsdp_utils/actor.py +++ b/miles/backends/fsdp_utils/actor.py @@ -358,7 +358,6 @@ def _train_core(self, rollout_id: int, rollout_data, external_data: dict[str, An loss_ctx = DiffusionLossContext( models=self.models, reference_models=self.reference_models, - teacher_models=self.teacher_models, train_pipeline_config=self.train_pipeline_config, sde_backend=self.sde_backend, args=self.args, @@ -538,7 +537,13 @@ def _forward_train_pair_batch( default_dtype=forward_dtype, ) - def _compute_noise_pred(model) -> dict[str, torch.Tensor]: + def _compute_noise_pred( + model, + *, + use_cfg: bool = prepared.use_cfg, + cfg_batching: bool = prepared.cfg_batching, + guidance_scale: float = prepared.guidance_scale, + ) -> dict[str, torch.Tensor]: with torch.autocast( "cuda", dtype=forward_dtype, @@ -551,12 +556,29 @@ def _compute_noise_pred(model) -> dict[str, torch.Tensor]: pos_cond=pos_cond_in, neg_cond=neg_cond_in, joint_cond=joint_cond_in, - use_cfg=prepared.use_cfg, - cfg_batching=prepared.cfg_batching, - guidance_scale=prepared.guidance_scale, + use_cfg=use_cfg, + cfg_batching=cfg_batching, + guidance_scale=guidance_scale, true_cfg_scale=prepared.true_cfg_scale, ) + # The frozen teacher runs before the training forward, so its gather never overlaps the activations. + teacher_pred = None + if prepared.teacher_guidance_scale is not None: + if prepared.component_name not in self.teacher_models: + 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( + teacher, + use_cfg=use_cfg, + cfg_batching=use_cfg and train_pipeline_config.cfg_batching, + guidance_scale=prepared.teacher_guidance_scale, + ) + # A no-grad forward leaves FSDP's root parameters gathered; sleep must move the shards. + reshard_model(teacher) + new_pred = _compute_noise_pred(prepared.model) # pi_old: the latest EMA, also when an async batch was sampled with the EMA before it. @@ -583,6 +605,7 @@ def _compute_noise_pred(model) -> dict[str, torch.Tensor]: new_pred=new_pred, old_pred=old_pred, ref_pred=ref_pred, + teacher_pred=teacher_pred, metrics=metrics, optim_step_idx=optim_step_idx, train_output_inputs=train_output_inputs, diff --git a/miles/backends/fsdp_utils/loss_hub/dmd2.py b/miles/backends/fsdp_utils/loss_hub/dmd2.py index 2388cd17f..0a8ecb90f 100644 --- a/miles/backends/fsdp_utils/loss_hub/dmd2.py +++ b/miles/backends/fsdp_utils/loss_hub/dmd2.py @@ -6,8 +6,6 @@ import torch -from miles.backends.fsdp_utils.ema import reshard_model -from miles.backends.fsdp_utils.input_dtype_policy import apply_input_dtype_policy 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.backends.fsdp_utils.metrics import record_rollout_train_abs_diff, step_metric_key @@ -24,7 +22,8 @@ def prepare_critic_batch( ) -> PreparedBatch: """SFT flow matching on the student's x0 predictions, conditioned on their rollout prompts. - The last step's samples are scored at their noisy inputs, so its grid points come from the scoring range. + The last step's samples are scored at their noisy inputs, so its grid points come from the scoring range and + the teacher runs on them too, with CFG over the rollout's negative cond when --dmd2-teacher-guidance-scale > 1. """ config = ctx.train_pipeline_config sft_batch = [ @@ -40,7 +39,7 @@ def prepare_critic_batch( num_train_timesteps = config.num_train_timesteps # Grid index i carries the unshifted sigma 1 - i / num_train_timesteps. grid_index_range = (round(num_train_timesteps * (1 - max_sigma)), round(num_train_timesteps * (1 - min_sigma))) - return prepare_sft_batch( + prepared = prepare_sft_batch( ctx, sft_batch, microbatch_id=microbatch_id, @@ -48,6 +47,24 @@ def prepare_critic_batch( pad_to_len=pad_to_len, grid_index_range=grid_index_range, ) + if grid_index_range is None: + return prepared + guidance_scale = ctx.args.dmd2_teacher_guidance_scale + if guidance_scale <= 1.0: + return dataclasses.replace(prepared, teacher_guidance_scale=guidance_scale) + envs = [pair["denoising_env"] for pair in batch] + if any(env.neg_cond_kwargs is None for env in envs): + raise ValueError( + "--dmd2-teacher-guidance-scale > 1 needs the rollout's negative cond, " + "which the engine returns only for requests that run CFG" + ) + pos_list = [entry["cond_kwargs"] for entry in sft_batch] + neg_list = [config.prepare_cond_kwargs(env.neg_cond_kwargs, ctx.device) for env in envs] + if config.cfg_batching: + joint_cond = config.collate_cond_for_sample_batch(pos_list + neg_list, ctx.device, pad_to_len=pad_to_len) + return dataclasses.replace(prepared, joint_cond=joint_cond, teacher_guidance_scale=guidance_scale) + neg_cond = config.collate_cond_for_sample_batch(neg_list, ctx.device, pad_to_len=pad_to_len) + return dataclasses.replace(prepared, neg_cond=neg_cond, teacher_guidance_scale=guidance_scale) def critic_loss_formula( @@ -58,6 +75,7 @@ def critic_loss_formula( new_pred: dict[str, torch.Tensor], old_pred: dict[str, torch.Tensor] | None, ref_pred: dict[str, torch.Tensor] | None, + teacher_pred: dict[str, torch.Tensor] | None = None, metrics: MetricBuffer, optim_step_idx: int, train_output_inputs: list, @@ -66,15 +84,15 @@ def critic_loss_formula( ) -> torch.Tensor: """The SFT loss in --dmd2-critic-loss-space. - On the last step it also keeps the critic's x0 at each noisy input, before that step's update. + On the last step it also keeps the critic's and the teacher's x0 at each noisy input, before that step's update. """ latents = prepared.latents["visual"] sigmas = prepared.extras["sigmas"]["visual"].view(len(batch), *([1] * (latents.ndim - 1))) if _is_scoring_step(ctx, optim_step_idx): x0_fake = latents - sigmas * new_pred["visual"].detach().float() - train_output_inputs.append( - (batch, prepared.component_name, latents, prepared.timesteps["visual"], sigmas, x0_fake) - ) + x0_real = latents - sigmas * teacher_pred["visual"].float() + for pair, real, fake in zip(batch, x0_real, x0_fake, strict=True): + train_output_inputs.append((pair["sample_index"], real, fake)) if ctx.args.dmd2_critic_loss_space == "x0": # x0 = x_sigma - sigma v, so the MSE on x0 weights the velocity MSE by sigma^2. x0_target = latents - sigmas * prepared.extras["target"]["visual"] @@ -98,79 +116,14 @@ def critic_loss_formula( def score_last_step_samples( ctx: DiffusionLossContext, train_pairs: list[dict], train_output_inputs: list ) -> dict[int, dict]: - """The teacher's x0 at each scored sample's noisy input, next to the critic's x0 kept there, by sample.""" - predictions = {} - for batch, component_name, latents, timesteps, sigmas, x0_fake in train_output_inputs: - teacher = ctx.teacher_models[component_name] - real_pred = _predict_velocity(ctx, teacher, batch, latents, timesteps, ctx.args.dmd2_teacher_guidance_scale) - for pair, x0_real, fake in zip(batch, latents - sigmas * real_pred, x0_fake, strict=True): - predictions[pair["sample_index"]] = {"x0_real": x0_real.cpu(), "x0_fake": fake.cpu()} - - # A no-grad forward leaves FSDP's root parameters gathered; sleep must move the shards. - for model in ctx.teacher_models.values(): - reshard_model(model) - return predictions + """The teacher's and the critic's x0 kept at each scored sample's noisy input, by sample.""" + return {index: {"x0_real": real.cpu(), "x0_fake": fake.cpu()} for index, real, fake in train_output_inputs} def _is_scoring_step(ctx: DiffusionLossContext, optim_step_idx: int) -> bool: return optim_step_idx == ctx.args.num_steps_per_rollout - 1 -def _predict_velocity( - ctx: DiffusionLossContext, - model: torch.nn.Module, - batch: list[dict], - latents: torch.Tensor, - timesteps: torch.Tensor, - guidance_scale: float, -) -> torch.Tensor: - """One velocity prediction, with CFG over the rollout's negative cond when ``guidance_scale > 1``.""" - config = ctx.train_pipeline_config - use_cfg = guidance_scale > 1.0 - envs = [pair["denoising_env"] for pair in batch] - if use_cfg and any(env.neg_cond_kwargs is None for env in envs): - raise ValueError( - "--dmd2-teacher-guidance-scale > 1 needs the rollout's negative cond, " - "which the engine returns only for requests that run CFG" - ) - pos_list = [config.prepare_cond_kwargs(env.pos_cond_kwargs, ctx.device) for env in envs] - neg_list = [config.prepare_cond_kwargs(env.neg_cond_kwargs, ctx.device) for env in envs] if use_cfg else [] - cfg_batching = use_cfg and config.cfg_batching - pos_cond = neg_cond = joint_cond = None - if cfg_batching: - joint_cond = config.collate_cond_for_sample_batch(pos_list + neg_list, ctx.device) - else: - pos_cond = config.collate_cond_for_sample_batch(pos_list, ctx.device) - if use_cfg: - neg_cond = config.collate_cond_for_sample_batch(neg_list, ctx.device) - - latents_in, timesteps_in, (pos_in, neg_in, joint_in) = apply_input_dtype_policy( - config.input_dtype_policy, - latents={"visual": latents}, - timesteps={"visual": config.process_timestep_as_input(timesteps)}, - conds=(pos_cond, neg_cond, joint_cond), - default_dtype=ctx.forward_dtype, - ) - with torch.autocast( - "cuda", - dtype=ctx.forward_dtype, - enabled=ctx.forward_dtype != torch.float32 and config.enable_autocast, - ): - pred = config.compute_noise_pred( - model=model, - latents_input=latents_in, - timesteps_input=timesteps_in, - pos_cond=pos_in, - neg_cond=neg_in, - joint_cond=joint_in, - use_cfg=use_cfg, - cfg_batching=cfg_batching, - guidance_scale=guidance_scale, - true_cfg_scale=None, - ) - return pred["visual"].float() - - def select_scored_pairs(ctx: DiffusionLossContext, train_pairs: list[dict]) -> list[dict]: """The pairs of the critic's last step, which it scored; the actor trains on these only.""" scores = ctx.external_data["critic"] @@ -231,6 +184,7 @@ def dmd2_loss_formula( new_pred: dict[str, torch.Tensor], old_pred: dict[str, torch.Tensor] | None, ref_pred: dict[str, torch.Tensor] | None, + teacher_pred: dict[str, torch.Tensor] | None = None, metrics: MetricBuffer, optim_step_idx: int, train_output_inputs: list, diff --git a/miles/backends/fsdp_utils/loss_hub/flow_grpo.py b/miles/backends/fsdp_utils/loss_hub/flow_grpo.py index 147208910..2608e608f 100644 --- a/miles/backends/fsdp_utils/loss_hub/flow_grpo.py +++ b/miles/backends/fsdp_utils/loss_hub/flow_grpo.py @@ -119,6 +119,7 @@ def flow_grpo_loss_formula( new_pred: dict[str, torch.Tensor], old_pred: dict[str, torch.Tensor] | None, ref_pred: dict[str, torch.Tensor] | None, + teacher_pred: dict[str, torch.Tensor] | None = None, metrics: MetricBuffer, optim_step_idx: int, train_output_inputs: list, diff --git a/miles/backends/fsdp_utils/loss_hub/nft.py b/miles/backends/fsdp_utils/loss_hub/nft.py index 88765cd94..f5ed466b1 100644 --- a/miles/backends/fsdp_utils/loss_hub/nft.py +++ b/miles/backends/fsdp_utils/loss_hub/nft.py @@ -113,6 +113,7 @@ def nft_loss_formula( new_pred: dict[str, torch.Tensor], old_pred: dict[str, torch.Tensor] | None, ref_pred: dict[str, torch.Tensor] | None, + teacher_pred: dict[str, torch.Tensor] | None = None, metrics: MetricBuffer, optim_step_idx: int, train_output_inputs: list, diff --git a/miles/backends/fsdp_utils/loss_hub/sft.py b/miles/backends/fsdp_utils/loss_hub/sft.py index df1ca25a3..9fb0a5552 100644 --- a/miles/backends/fsdp_utils/loss_hub/sft.py +++ b/miles/backends/fsdp_utils/loss_hub/sft.py @@ -127,6 +127,7 @@ def sft_loss_formula( new_pred: dict[str, torch.Tensor], old_pred: dict[str, torch.Tensor] | None, ref_pred: dict[str, torch.Tensor] | None, + teacher_pred: dict[str, torch.Tensor] | None = None, metrics: MetricBuffer, optim_step_idx: int, train_output_inputs: list, diff --git a/miles/backends/fsdp_utils/loss_hub/types.py b/miles/backends/fsdp_utils/loss_hub/types.py index 129d08cad..449d49a34 100644 --- a/miles/backends/fsdp_utils/loss_hub/types.py +++ b/miles/backends/fsdp_utils/loss_hub/types.py @@ -26,7 +26,6 @@ class DiffusionLossContext: rollout_id: int = 0 dp_rank: int = 0 reference_models: dict[str, torch.nn.Module] = field(default_factory=dict) - teacher_models: dict[str, torch.nn.Module] = field(default_factory=dict) external_data: dict[str, Any] = field(default_factory=dict) @@ -70,3 +69,5 @@ class PreparedBatch: joint_cond: dict | None advantage: torch.Tensor 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 diff --git a/tests/fast/backends/fsdp_utils/test_loss_hub_dmd2.py b/tests/fast/backends/fsdp_utils/test_loss_hub_dmd2.py index c05447b30..aa3a08501 100644 --- a/tests/fast/backends/fsdp_utils/test_loss_hub_dmd2.py +++ b/tests/fast/backends/fsdp_utils/test_loss_hub_dmd2.py @@ -6,15 +6,17 @@ (the critic's K steps are the SFT loss on the student's samples; the last step, whose samples get scored, draws grid points whose unshifted sigma lies in --dmd2-score-sigma-range, default [0.02, 0.98]) + │ + the last step also asks the trunk for the teacher, PreparedBatch.teacher_guidance_scale, + with the rollout's neg cond collated for its CFG) + │ + the trunk runs the teacher without grad at x_s before the critic's training forward ──► v_real │ critic_loss_formula ──► sft_loss_formula on v, or on x0 = x_s - sigma v under --dmd2-critic-loss-space x0; - on the last step it also keeps, per micro-batch, - x_s = that step's noisy input, sigma, and x0_fake = x_s - sigma v_fake from the - training forward, i.e. the critic before the last update + on the last step it also keeps, per sample, x0_fake = x_s - sigma v_fake from the + training forward, i.e. the critic before the last update, and x0_real = x_s - sigma v_real │ - score_last_step_samples, without grad after the critic's steps, per kept micro-batch: - teacher, CFG --dmd2-teacher-guidance-scale over the rollout's neg cond ──► x0_real = x_s - sigma v_real - ──► {sample_index: {"x0_real", "x0_fake"}}; the teacher is resharded so sleep moves its shards + score_last_step_samples, after the critic's steps ──► {sample_index: {"x0_real", "x0_fake"}} on the host │ ctx.external_data["critic"] on the paired actor rank select_scored_pairs ──► the actor's train-input hook keeps only the scored pairs, i.e. the critic's last step prepare_generator_batch ──► the student's unguided step i on the rollout input x_i @@ -30,10 +32,12 @@ test_critic_loss_is_the_sft_loss loss and metrics == sft_loss_formula on every step test_x0_critic_loss_weights_the_velocity_mse x0 loss == x0 MSE == sigma^2 * velocity MSE, input intact test_only_the_last_step_keeps_scoring_inputs earlier steps keep nothing, so only the last step is scored - test_scores_match_separate_forwards_at_the_kept_input fused scores == critic and teacher forwards run apart at x_s - test_teacher_runs_cfg_and_the_critic_runs_unguided CFG combine for the teacher only - test_teacher_cfg_needs_the_rollout_negative_cond rejected instead of a forward without text - test_scoring_reshards_the_teacher teacher resharded after its no-grad forwards + test_earlier_steps_ask_for_no_teacher no teacher scale, no negative cond before the last step + test_last_step_asks_for_the_guided_teacher teacher scale and the neg cond collated per CFG batching + test_unguided_teacher_needs_no_negative_cond scale 1: the teacher reads only the positive cond + test_teacher_cfg_needs_the_rollout_negative_cond rejected at prepare instead of a forward without text + test_scores_are_x0_at_the_kept_input x0_fake and x0_real == x_s - sigma v of each forward + test_teacher_runs_cfg_and_the_critic_runs_unguided CFG combine for the teacher only; kept x0 carry no grad test_actor_keeps_the_critic_last_step_pairs same shard ──► the actor trains on the scored 1/K only test_scores_outside_the_shard_are_rejected a broken rank pairing fails instead of shrinking the batch test_generator_batch_is_the_student_step_on_its_input x_i, t_i, sigma_i and the positive cond, no CFG @@ -73,7 +77,7 @@ class _CondVelocity(nn.Module): def __init__(self, scale): super().__init__() - self.scale = scale + self.scale = nn.Parameter(torch.tensor(float(scale))) def forward(self, hidden_states, timestep, return_dict, encoder_hidden_states, pooled_projections): text = encoder_hidden_states.mean(dim=(1, 2)).view(-1, 1, 1, 1) @@ -113,10 +117,9 @@ def _pairs(num_pairs, with_neg=True): ] -def _ctx(teacher_guidance_scale=3.0, critic_scale=1.0, teacher_scale=1.0): +def _ctx(teacher_guidance_scale=3.0, critic_scale=1.0): return DiffusionLossContext( models={"transformer": _CondVelocity(critic_scale)}, - teacher_models={"transformer": _CondVelocity(teacher_scale)}, train_pipeline_config=SD3TrainPipelineConfig(), sde_backend=None, args=Namespace( @@ -137,25 +140,51 @@ def _ctx(teacher_guidance_scale=3.0, critic_scale=1.0, teacher_scale=1.0): ) -def _critic_step(ctx, pairs, optim_step_idx, train_output_inputs, metrics=None): - """One critic optimizer step as _train_core runs it: prepare, the critic's training forward, the loss hook.""" +def _forward(config, model, prepared, *, use_cfg, cfg_batching, guidance_scale): + return config.compute_noise_pred( + model=model, + latents_input=prepared.latents, + timesteps_input=prepared.timesteps_for_model, + pos_cond=prepared.pos_cond, + neg_cond=prepared.neg_cond, + joint_cond=prepared.joint_cond, + use_cfg=use_cfg, + cfg_batching=cfg_batching, + guidance_scale=guidance_scale, + true_cfg_scale=None, + ) + + +def _critic_step(ctx, pairs, optim_step_idx, train_output_inputs, metrics=None, teacher=None): + """One critic optimizer step as _train_core runs it: prepare, the teacher forward it asks for, the critic's + training forward, the loss hook.""" + config = ctx.train_pipeline_config + teacher = _CondVelocity(1.0) if teacher is None else teacher steps = [] for start in range(0, len(pairs), ctx.args.micro_batch_size): batch = pairs[start : start + ctx.args.micro_batch_size] prepared = dmd2.prepare_critic_batch( ctx, batch, microbatch_id=optim_step_idx * 10 + start, optim_step_idx=optim_step_idx ) - new_pred = ctx.train_pipeline_config.compute_noise_pred( - model=prepared.model, - latents_input=prepared.latents, - timesteps_input=prepared.timesteps_for_model, - pos_cond=prepared.pos_cond, - neg_cond=None, - joint_cond=None, + teacher_pred = None + if prepared.teacher_guidance_scale is not None: + use_cfg = prepared.teacher_guidance_scale > 1.0 + with torch.no_grad(): + teacher_pred = _forward( + config, + teacher, + prepared, + use_cfg=use_cfg, + cfg_batching=use_cfg and config.cfg_batching, + guidance_scale=prepared.teacher_guidance_scale, + ) + new_pred = _forward( + config, + prepared.model, + prepared, use_cfg=prepared.use_cfg, cfg_batching=prepared.cfg_batching, guidance_scale=prepared.guidance_scale, - true_cfg_scale=None, ) loss = dmd2.critic_loss_formula( ctx, @@ -164,6 +193,7 @@ def _critic_step(ctx, pairs, optim_step_idx, train_output_inputs, metrics=None): new_pred=new_pred, old_pred=None, ref_pred=None, + teacher_pred=teacher_pred, metrics=metrics or _Metrics(), optim_step_idx=optim_step_idx, train_output_inputs=train_output_inputs, @@ -283,39 +313,88 @@ def test_only_the_last_step_keeps_scoring_inputs(): assert inputs == [] _critic_step(ctx, pairs[6:], CRITIC_STEPS - 1, inputs) - assert len(inputs) == 2 # one entry per micro-batch of the last step + assert [index for index, _, _ in inputs] == [106, 107, 108] scores = dmd2.score_last_step_samples(ctx, pairs, inputs) assert list(scores) == [106, 107, 108] -def test_scores_match_separate_forwards_at_the_kept_input(): +def test_earlier_steps_ask_for_no_teacher(): + ctx = _ctx(teacher_guidance_scale=3.0) + for optim_step_idx in range(CRITIC_STEPS - 1): + prepared = dmd2.prepare_critic_batch(ctx, _pairs(2), microbatch_id=0, optim_step_idx=optim_step_idx) + assert prepared.teacher_guidance_scale is None + assert prepared.neg_cond is None and prepared.joint_cond is None + + +@pytest.mark.parametrize("cfg_batching", [False, True]) +def test_last_step_asks_for_the_guided_teacher(cfg_batching): + ctx = _ctx(teacher_guidance_scale=3.0) + config = ctx.train_pipeline_config + config.cfg_batching = cfg_batching + pairs = _pairs(2) + + prepared = dmd2.prepare_critic_batch(ctx, pairs, microbatch_id=0, optim_step_idx=CRITIC_STEPS - 1) + + assert prepared.teacher_guidance_scale == 3.0 + assert not prepared.use_cfg and not prepared.cfg_batching + pos_list = [config.prepare_cond_kwargs(pair["denoising_env"].pos_cond_kwargs, ctx.device) for pair in pairs] + neg_list = [config.prepare_cond_kwargs(pair["denoising_env"].neg_cond_kwargs, ctx.device) for pair in pairs] + pos = config.collate_cond_for_sample_batch(pos_list, ctx.device)["encoder_hidden_states"] + assert torch.equal(prepared.pos_cond["encoder_hidden_states"], pos) + if cfg_batching: + joint = config.collate_cond_for_sample_batch(pos_list + neg_list, ctx.device)["encoder_hidden_states"] + assert prepared.neg_cond is None + assert torch.equal(prepared.joint_cond["encoder_hidden_states"], joint) + else: + neg = config.collate_cond_for_sample_batch(neg_list, ctx.device)["encoder_hidden_states"] + assert prepared.joint_cond is None + assert torch.equal(prepared.neg_cond["encoder_hidden_states"], neg) + + +def test_unguided_teacher_needs_no_negative_cond(): + ctx = _ctx(teacher_guidance_scale=1.0) + prepared = dmd2.prepare_critic_batch( + ctx, _pairs(2, with_neg=False), microbatch_id=0, optim_step_idx=CRITIC_STEPS - 1 + ) + assert prepared.teacher_guidance_scale == 1.0 + assert prepared.neg_cond is None and prepared.joint_cond is None + + +def test_teacher_cfg_needs_the_rollout_negative_cond(): ctx = _ctx(teacher_guidance_scale=3.0) + with pytest.raises(ValueError, match="needs the rollout's negative cond"): + dmd2.prepare_critic_batch(ctx, _pairs(2, with_neg=False), microbatch_id=0, optim_step_idx=CRITIC_STEPS - 1) + # Earlier steps run no teacher, so they take pairs without a negative cond. + dmd2.prepare_critic_batch(ctx, _pairs(2, with_neg=False), microbatch_id=0, optim_step_idx=0) + + +def test_scores_are_x0_at_the_kept_input(): + ctx = _ctx(teacher_guidance_scale=1.0) ctx.models["transformer"] = _NoisyInputVelocity() pairs = _pairs(5) inputs = [] - steps = _critic_step(ctx, pairs, CRITIC_STEPS - 1, inputs) + steps = _critic_step(ctx, pairs, CRITIC_STEPS - 1, inputs, teacher=_NoisyInputVelocity()) scores = dmd2.score_last_step_samples(ctx, pairs, inputs) assert list(scores) == [100, 101, 102, 103, 104] for batch, prepared, _, _ in steps: x_s = prepared.latents["visual"] - timesteps = prepared.timesteps["visual"] + velocity = x_s + prepared.timesteps_for_model["visual"].view(-1, 1, 1, 1) sigma = prepared.extras["sigmas"]["visual"].view(-1, 1, 1, 1) - fake = dmd2._predict_velocity(ctx, ctx.models["transformer"], batch, x_s, timesteps, 1.0) - real = dmd2._predict_velocity(ctx, ctx.teacher_models["transformer"], batch, x_s, timesteps, 3.0) for n, pair in enumerate(batch): - assert torch.equal(scores[pair["sample_index"]]["x0_fake"], x_s[n] - sigma[n] * fake[n]) - assert torch.equal(scores[pair["sample_index"]]["x0_real"], x_s[n] - sigma[n] * real[n]) + assert torch.equal(scores[pair["sample_index"]]["x0_fake"], x_s[n] - sigma[n] * velocity[n]) + assert torch.equal(scores[pair["sample_index"]]["x0_real"], x_s[n] - sigma[n] * velocity[n]) def test_teacher_runs_cfg_and_the_critic_runs_unguided(): - ctx = _ctx(teacher_guidance_scale=3.0, teacher_scale=1.0, critic_scale=2.0) + ctx = _ctx(teacher_guidance_scale=3.0, critic_scale=2.0) + teacher = _CondVelocity(1.0) pairs = _pairs(2) inputs = [] - [(_, prepared, _, _)] = _critic_step(ctx, pairs, CRITIC_STEPS - 1, inputs) + [(_, prepared, _, loss)] = _critic_step(ctx, pairs, CRITIC_STEPS - 1, inputs, teacher=teacher) scores = dmd2.score_last_step_samples(ctx, pairs, inputs) x_s = prepared.latents["visual"] @@ -326,31 +405,11 @@ def test_teacher_runs_cfg_and_the_critic_runs_unguided(): scores[pair["sample_index"]]["x0_real"], x_s[n] - sigma[n] * (neg + 3.0 * (pos - neg)) ) torch.testing.assert_close(scores[pair["sample_index"]]["x0_fake"], x_s[n] - sigma[n] * 2.0 * pos) - - -def test_teacher_cfg_needs_the_rollout_negative_cond(): - ctx = _ctx(teacher_guidance_scale=3.0) - inputs = [] - _critic_step(ctx, _pairs(2, with_neg=False), CRITIC_STEPS - 1, inputs) - with pytest.raises(ValueError, match="needs the rollout's negative cond"): - dmd2.score_last_step_samples(ctx, _pairs(2, with_neg=False), inputs) - # Unguided, the teacher reads only the positive cond. - ctx = _ctx(teacher_guidance_scale=1.0) - inputs = [] - _critic_step(ctx, _pairs(2, with_neg=False), CRITIC_STEPS - 1, inputs) - dmd2.score_last_step_samples(ctx, _pairs(2, with_neg=False), inputs) - - -def test_scoring_reshards_the_teacher(monkeypatch): - resharded = [] - monkeypatch.setattr(dmd2, "reshard_model", resharded.append) - ctx = _ctx() - inputs = [] - _critic_step(ctx, _pairs(2), CRITIC_STEPS - 1, inputs) - - dmd2.score_last_step_samples(ctx, _pairs(2), inputs) - - assert resharded == [ctx.teacher_models["transformer"]] + assert not scores[pair["sample_index"]]["x0_real"].requires_grad + assert not scores[pair["sample_index"]]["x0_fake"].requires_grad + loss.backward() + assert ctx.models["transformer"].scale.grad is not None + assert teacher.scale.grad is None def test_actor_keeps_the_critic_last_step_pairs(): diff --git a/tests/fast/backends/fsdp_utils/test_reference_models.py b/tests/fast/backends/fsdp_utils/test_reference_models.py index f57aaadfb..85798c423 100644 --- a/tests/fast/backends/fsdp_utils/test_reference_models.py +++ b/tests/fast/backends/fsdp_utils/test_reference_models.py @@ -2,7 +2,7 @@ full / new / saved LoRA -> actor (trainable) ---> loss ---> gradients + optimizer step +-> reference (full or LoRA) --no_grad--/ - +-> teacher (LoRA) -----------no_grad--/ + +-> teacher (LoRA) -----------no_grad--/ runs first, when prepare asks for it two components ---> select the matching role component LoRA base reference ---> disable adapter ---> adapters and their gradients back on the actor FSDP2 kept-gathered ---> lora_base forward ---> next step still trains the adapters @@ -84,11 +84,16 @@ def fsdp_parallel_plan(self, model): class TinyPipelineConfig: input_dtype_policy = {} + cfg_batching = False + + def __init__(self): + self.noise_pred_calls = [] def postprocess_model_after_materialize(self, model): pass def compute_noise_pred(self, *, model, latents_input, **kwargs): + self.noise_pred_calls.append((model, kwargs)) return {"visual": model(latents_input["visual"])} @@ -122,7 +127,7 @@ def save_component_lora_adapters(path): return adapter_paths -def load_actor_forward_method(): +def load_actor_forward_method(reshard_model=reshard_model): path = Path(__file__).resolve().parents[4] / "miles/backends/fsdp_utils/actor.py" source = ast.parse(path.read_text()) actor = next(node for node in source.body if isinstance(node, ast.ClassDef) and node.name == "FSDPTrainRayActor") @@ -141,7 +146,16 @@ def load_actor_forward_method(): def make_actor_forward_harness( - models, reference_models, component, inputs, ref_mode, *, loss_type="policy_loss", ema_optimizer=None + models, + reference_models, + component, + inputs, + ref_mode, + *, + loss_type="policy_loss", + ema_optimizer=None, + teacher_models=None, + teacher_guidance_scale=None, ): observed = {} prepared = SimpleNamespace( @@ -156,17 +170,19 @@ def make_actor_forward_harness( cfg_batching=False, guidance_scale=1.0, true_cfg_scale=None, + teacher_guidance_scale=teacher_guidance_scale, ) def prepare(ctx, batch, **kwargs): observed["prepare_kwargs"] = kwargs return prepared - def loss_formula(ctx, batch, prepared, *, new_pred, old_pred, ref_pred, **kwargs): - predictions = {"new_pred": new_pred, "old_pred": old_pred, "ref_pred": ref_pred} + def loss_formula(ctx, batch, prepared, *, new_pred, old_pred, ref_pred, teacher_pred, **kwargs): + predictions = {"new_pred": new_pred, "old_pred": old_pred, "ref_pred": ref_pred, "teacher_pred": teacher_pred} observed.update({name: pred["visual"] for name, pred in predictions.items() if pred is not None}) observed["formula_kwargs"] = kwargs - return (new_pred["visual"] - ref_pred["visual"]).square().mean() + target = torch.zeros_like(new_pred["visual"]) if ref_pred is None else ref_pred["visual"] + return (new_pred["visual"] - target).square().mean() harness = SimpleNamespace( args=Namespace(ref_mode=ref_mode, loss_type=loss_type), @@ -174,6 +190,7 @@ def loss_formula(ctx, batch, prepared, *, new_pred, old_pred, ref_pred, **kwargs ema_optimizer=ema_optimizer, model=torch.nn.ModuleDict(models), reference_models=reference_models, + teacher_models={} if teacher_models is None else teacher_models, train_pipeline_config=TinyPipelineConfig(), _forward_dtype=torch.float32, loss_hooks=SimpleNamespace(prepare=prepare, formula=loss_formula), @@ -511,3 +528,81 @@ def test_the_trunk_hands_the_hooks_their_own_counters_and_the_one_list(): assert observed["prepare_kwargs"] == {"microbatch_id": 7, "optim_step_idx": 2, "pad_to_len": None} assert observed["formula_kwargs"]["optim_step_idx"] == 2 assert observed["formula_kwargs"]["train_output_inputs"] is train_output_inputs + + +def _teacher_harness(teacher_guidance_scale, *, with_teacher=True): + actor, teacher = TinyComponent(), TinyComponent() + order = [] + actor.register_forward_hook(lambda *_: order.append("actor")) + teacher.register_forward_hook(lambda *_: order.append("teacher")) + harness, observed = make_actor_forward_harness( + {"transformer": actor}, + {}, + "transformer", + torch.ones(2, 3), + "none", + teacher_models={"transformer": teacher} if with_teacher else None, + teacher_guidance_scale=teacher_guidance_scale, + ) + observed["order"] = order + return harness, observed, actor, teacher + + +def _run_forward(harness, reshard_model=reshard_model): + return load_actor_forward_method(reshard_model=reshard_model)( + harness, None, [], microbatch_id=0, optim_step_idx=0, train_output_inputs=[], metrics=None + ) + + +@pytest.mark.parametrize("cfg_batching", [False, True]) +def test_the_teacher_runs_first_without_grad_with_its_own_cfg(cfg_batching): + harness, observed, actor, teacher = _teacher_harness(3.0) + harness.train_pipeline_config.cfg_batching = cfg_batching + resharded = [] + + _run_forward(harness, reshard_model=resharded.append).backward() + + assert observed["order"] == ["teacher", "actor"] + assert resharded == [teacher] + assert not observed["teacher_pred"].requires_grad + with torch.no_grad(): + torch.testing.assert_close(observed["teacher_pred"], teacher(torch.ones(2, 3))) + assert actor.block.proj.weight.grad is not None and teacher.block.proj.weight.grad is None + [(teacher_model, teacher_call), (actor_model, actor_call)] = harness.train_pipeline_config.noise_pred_calls + assert teacher_model is teacher and actor_model is actor + assert (teacher_call["use_cfg"], teacher_call["cfg_batching"], teacher_call["guidance_scale"]) == ( + True, + cfg_batching, + 3.0, + ) + assert (actor_call["use_cfg"], actor_call["cfg_batching"], actor_call["guidance_scale"]) == (False, False, 1.0) + + +def test_an_unguided_teacher_runs_without_cfg(): + harness, _, _, teacher = _teacher_harness(1.0) + harness.train_pipeline_config.cfg_batching = True + + _run_forward(harness, reshard_model=lambda model: None) + + [(teacher_model, teacher_call), _] = harness.train_pipeline_config.noise_pred_calls + assert teacher_model is teacher + assert (teacher_call["use_cfg"], teacher_call["cfg_batching"], teacher_call["guidance_scale"]) == ( + False, + False, + 1.0, + ) + + +def test_no_teacher_forward_unless_the_prepare_hook_asks(): + harness, observed, _, teacher = _teacher_harness(None) + + _run_forward(harness) + + assert teacher.forward_count.item() == 0 and "teacher_pred" not in observed + assert observed["order"] == ["actor"] + + +def test_a_teacher_request_without_a_teacher_is_rejected(): + harness, _, _, _ = _teacher_harness(3.0, with_teacher=False) + with pytest.raises(ValueError, match="--teacher-load"): + _run_forward(harness) 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 ccb573cc9..b01bf3384 100644 --- a/tests/fast/backends/fsdp_utils/test_train_input_hook.py +++ b/tests/fast/backends/fsdp_utils/test_train_input_hook.py @@ -60,7 +60,6 @@ def _actor(train_input, train_output, forwarded, **args): lists=lists, models={}, reference_models={}, - teacher_models={}, train_pipeline_config=None, sde_backend=None, args=Namespace( diff --git a/tests/fast/utils/test_reference_arguments.py b/tests/fast/utils/test_reference_arguments.py index 890b55844..33231e017 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 ---> loaded for whichever hook reads ctx.teacher_models; nothing in args says who will + teacher ---> run by the trunk when a prepare hook asks for it; nothing in args says which 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 From 44eb2b6b7671915594004af2cc0314c01225fbf7 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Wed, 11 Nov 2026 05:37:58 +0000 Subject: [PATCH 25/33] fix(fsdp): run the teacher forward without the student's true_cfg_scale --- miles/backends/fsdp_utils/actor.py | 4 +++- .../fast/backends/fsdp_utils/test_reference_models.py | 11 ++++++++--- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/miles/backends/fsdp_utils/actor.py b/miles/backends/fsdp_utils/actor.py index de10e8ad9..b948f444c 100644 --- a/miles/backends/fsdp_utils/actor.py +++ b/miles/backends/fsdp_utils/actor.py @@ -543,6 +543,7 @@ def _compute_noise_pred( use_cfg: bool = prepared.use_cfg, cfg_batching: bool = prepared.cfg_batching, guidance_scale: float = prepared.guidance_scale, + true_cfg_scale: float | None = prepared.true_cfg_scale, ) -> dict[str, torch.Tensor]: with torch.autocast( "cuda", @@ -559,7 +560,7 @@ def _compute_noise_pred( use_cfg=use_cfg, cfg_batching=cfg_batching, guidance_scale=guidance_scale, - true_cfg_scale=prepared.true_cfg_scale, + true_cfg_scale=true_cfg_scale, ) # The frozen teacher runs before the training forward, so its gather never overlaps the activations. @@ -575,6 +576,7 @@ def _compute_noise_pred( use_cfg=use_cfg, cfg_batching=use_cfg and train_pipeline_config.cfg_batching, guidance_scale=prepared.teacher_guidance_scale, + true_cfg_scale=None, ) # A no-grad forward leaves FSDP's root parameters gathered; sleep must move the shards. reshard_model(teacher) diff --git a/tests/fast/backends/fsdp_utils/test_reference_models.py b/tests/fast/backends/fsdp_utils/test_reference_models.py index 85798c423..e90e271a2 100644 --- a/tests/fast/backends/fsdp_utils/test_reference_models.py +++ b/tests/fast/backends/fsdp_utils/test_reference_models.py @@ -156,6 +156,7 @@ def make_actor_forward_harness( ema_optimizer=None, teacher_models=None, teacher_guidance_scale=None, + true_cfg_scale=None, ): observed = {} prepared = SimpleNamespace( @@ -169,7 +170,7 @@ def make_actor_forward_harness( use_cfg=False, cfg_batching=False, guidance_scale=1.0, - true_cfg_scale=None, + true_cfg_scale=true_cfg_scale, teacher_guidance_scale=teacher_guidance_scale, ) @@ -530,7 +531,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): +def _teacher_harness(teacher_guidance_scale, *, with_teacher=True, true_cfg_scale=None): actor, teacher = TinyComponent(), TinyComponent() order = [] actor.register_forward_hook(lambda *_: order.append("actor")) @@ -543,6 +544,7 @@ def _teacher_harness(teacher_guidance_scale, *, with_teacher=True): "none", teacher_models={"transformer": teacher} if with_teacher else None, teacher_guidance_scale=teacher_guidance_scale, + true_cfg_scale=true_cfg_scale, ) observed["order"] = order return harness, observed, actor, teacher @@ -556,7 +558,8 @@ def _run_forward(harness, reshard_model=reshard_model): @pytest.mark.parametrize("cfg_batching", [False, True]) def test_the_teacher_runs_first_without_grad_with_its_own_cfg(cfg_batching): - harness, observed, actor, teacher = _teacher_harness(3.0) + # true_cfg_scale overrides guidance_scale in cfg_combine, so the student's must not reach the teacher. + harness, observed, actor, teacher = _teacher_harness(3.0, true_cfg_scale=7.0) harness.train_pipeline_config.cfg_batching = cfg_batching resharded = [] @@ -575,7 +578,9 @@ def test_the_teacher_runs_first_without_grad_with_its_own_cfg(cfg_batching): cfg_batching, 3.0, ) + assert teacher_call["true_cfg_scale"] is None assert (actor_call["use_cfg"], actor_call["cfg_batching"], actor_call["guidance_scale"]) == (False, False, 1.0) + assert actor_call["true_cfg_scale"] == 7.0 def test_an_unguided_teacher_runs_without_cfg(): From b9e206a70eb65d0c8de69b5ef6c83cb44e026a50 Mon Sep 17 00:00:00 2001 From: rockdu Date: Wed, 11 Nov 2026 02:31:42 -0800 Subject: [PATCH 26/33] refactor(dmd2): pull the teacher request out of prepare_critic_batch prepare_critic_batch did three things in one body: build the SFT batch, pick the scoring step's grid range, and collate the teacher's CFG inputs. The teacher part is its own function now, _request_teacher_forward, and the two helpers it shared with #351 are back, so the critic's prepare reads as SFT plus the last step's teacher request. No behaviour change. --- miles/backends/fsdp_utils/loss_hub/dmd2.py | 50 ++++++++++++++-------- 1 file changed, 31 insertions(+), 19 deletions(-) diff --git a/miles/backends/fsdp_utils/loss_hub/dmd2.py b/miles/backends/fsdp_utils/loss_hub/dmd2.py index 0a8ecb90f..371679c19 100644 --- a/miles/backends/fsdp_utils/loss_hub/dmd2.py +++ b/miles/backends/fsdp_utils/loss_hub/dmd2.py @@ -23,32 +23,44 @@ def prepare_critic_batch( """SFT flow matching on the student's x0 predictions, conditioned on their rollout prompts. The last step's samples are scored at their noisy inputs, so its grid points come from the scoring range and - the teacher runs on them too, with CFG over the rollout's negative cond when --dmd2-teacher-guidance-scale > 1. + the teacher runs on them too. """ + scoring = _is_scoring_step(ctx, optim_step_idx) + prepared = prepare_sft_batch( + ctx, + _sft_batch(ctx, batch), + microbatch_id=microbatch_id, + optim_step_idx=optim_step_idx, + pad_to_len=pad_to_len, + grid_index_range=_score_grid_index_range(ctx) if scoring else None, + ) + return _request_teacher_forward(ctx, batch, prepared, pad_to_len=pad_to_len) if scoring else prepared + + +def _sft_batch(ctx: DiffusionLossContext, batch: list[dict]) -> list[dict]: config = ctx.train_pipeline_config - sft_batch = [ + return [ { "latent": {"visual": pair["x0"]}, "cond_kwargs": config.prepare_cond_kwargs(pair["denoising_env"].pos_cond_kwargs, ctx.device), } for pair in batch ] - grid_index_range = None - if _is_scoring_step(ctx, optim_step_idx): - min_sigma, max_sigma = ctx.args.dmd2_score_sigma_range - num_train_timesteps = config.num_train_timesteps - # Grid index i carries the unshifted sigma 1 - i / num_train_timesteps. - grid_index_range = (round(num_train_timesteps * (1 - max_sigma)), round(num_train_timesteps * (1 - min_sigma))) - prepared = prepare_sft_batch( - ctx, - sft_batch, - microbatch_id=microbatch_id, - optim_step_idx=optim_step_idx, - pad_to_len=pad_to_len, - grid_index_range=grid_index_range, - ) - if grid_index_range is None: - return prepared + + +def _score_grid_index_range(ctx: DiffusionLossContext) -> tuple[int, int]: + min_sigma, max_sigma = ctx.args.dmd2_score_sigma_range + num_train_timesteps = ctx.train_pipeline_config.num_train_timesteps + # Grid index i carries the unshifted sigma 1 - i / num_train_timesteps. + return round(num_train_timesteps * (1 - max_sigma)), round(num_train_timesteps * (1 - min_sigma)) + + +def _request_teacher_forward( + ctx: DiffusionLossContext, batch: list[dict], prepared: PreparedBatch, *, pad_to_len: int | None +) -> PreparedBatch: + """Ask the trunk for the teacher at --dmd2-teacher-guidance-scale on this batch, with the rollout's negative + cond collated for its CFG when the scale needs one.""" + config = ctx.train_pipeline_config guidance_scale = ctx.args.dmd2_teacher_guidance_scale if guidance_scale <= 1.0: return dataclasses.replace(prepared, teacher_guidance_scale=guidance_scale) @@ -58,7 +70,7 @@ def prepare_critic_batch( "--dmd2-teacher-guidance-scale > 1 needs the rollout's negative cond, " "which the engine returns only for requests that run CFG" ) - pos_list = [entry["cond_kwargs"] for entry in sft_batch] + pos_list = [config.prepare_cond_kwargs(env.pos_cond_kwargs, ctx.device) for env in envs] neg_list = [config.prepare_cond_kwargs(env.neg_cond_kwargs, ctx.device) for env in envs] if config.cfg_batching: joint_cond = config.collate_cond_for_sample_batch(pos_list + neg_list, ctx.device, pad_to_len=pad_to_len) From 7dbfaf1c79bd8bc238678b3d436b0588dd9b5354 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Tue, 10 Nov 2026 08:04:16 +0000 Subject: [PATCH 27/33] test(e2e): run the H3 DMD2 recipe as a 2-GPU proxy in CI The DMD2 recipe only knew its 2 x 8 topology. Give it the knobs an e2e needs: --num-nodes / --num-gpus-per-node (one node starts its own ray cluster), --critic-steps-per-rollout, --eval-interval 0 / --save-interval 0 to drop eval and checkpoints (0 used to reach should_run_periodic_action's modulo), --fsdp-cpu-offload and --master-dtype. The three 31B models do not fit two GPUs with their optimizers, so the proxy keeps parameters, gradients and optimizer states in host memory with a bf16 master and steps on the CPU. tests/e2e/short/test_h3_t2va_dmd2_2xGPU.py runs 2 rollouts of 4 prompts (2 critic steps of 2, 1 student step on the last 2) under --deterministic-mode and checks the critic loss and grad norm, the student grad norm and the DMD2 metrics against the recorded standard. The 16-GPU defaults are unchanged. Co-Authored-By: Claude Mythos 5.1 --- docs/models/h3/h3.md | 13 +++++ ..._diffusion_dmd2_h3_t2va_16gpu_multinode.py | 44 +++++++++++---- tests/e2e/short/test_h3_t2va_dmd2_2xGPU.py | 54 +++++++++++++++++++ 3 files changed, 100 insertions(+), 11 deletions(-) create mode 100644 tests/e2e/short/test_h3_t2va_dmd2_2xGPU.py diff --git a/docs/models/h3/h3.md b/docs/models/h3/h3.md index 361e0ebf5..9b68bd168 100644 --- a/docs/models/h3/h3.md +++ b/docs/models/h3/h3.md @@ -81,6 +81,19 @@ MILES_SCRIPT_EXTERNAL_RAY=1 python3 scripts/run_diffusion_dmd2_h3_t2va_16gpu_mul MILES_SCRIPT_EXTERNAL_RAY=1 python3 scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py --reference fasth3 ``` +The same script runs on one node for smoke runs; `tests/e2e/short/test_h3_t2va_dmd2_2xGPU.py` runs +this 2-GPU proxy in CI (2 rollouts of 4 prompts, 2 critic steps, no eval or checkpoints). Below +16 GPUs the two 31B optimizers do not fit next to the models, so `--fsdp-cpu-offload` keeps +parameters, gradients and optimizer states in host memory (about 1.1 TB; the optimizer steps on the +CPU). The master stays fp32: H3 pins proj_in / time_embedder / proj_out to fp32, and FSDP2 wants one +original dtype across a group's trainable parameters. + +```bash +python3 scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py --num-nodes 1 --num-gpus-per-node 2 \ + --rollout-batch-size 4 --critic-steps-per-rollout 2 --num-rollout 2 --eval-interval 0 \ + --save-interval 0 --fsdp-cpu-offload +``` + What to watch: | Signal | Where | Reading | diff --git a/scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py b/scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py index e13c3ed20..b97892f75 100644 --- a/scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py +++ b/scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py @@ -34,6 +34,15 @@ Usage (after the multi-node bring-up, on the head node): MILES_SCRIPT_EXTERNAL_RAY=1 python3 scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py + +Single node, for smoke runs and the e2e CI: the script starts its own ray cluster. Two GPUs hold the +rollout engine (tp2) and FSDP DP=2 over the student, the critic and the teacher only with their +parameters, gradients and optimizer states in host memory (--fsdp-cpu-offload; about 1.1 TB). The +master stays fp32: H3 keeps proj_in / time_embedder / proj_out in fp32, and FSDP2 wants one original +dtype across a group's trainable parameters, which a bf16 master would break for full-parameter training. + python3 scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py --num-nodes 1 --num-gpus-per-node 2 \ + --rollout-batch-size 4 --critic-steps-per-rollout 2 --num-rollout 2 --eval-interval 0 \ + --save-interval 0 --fsdp-cpu-offload """ import hashlib @@ -80,10 +89,18 @@ @dataclass class ScriptArgs(U.ExecuteTrainConfig): num_rollout: int = 200 - # 5 critic steps x 64 samples; the student steps on the last 64. + # critic_steps_per_rollout critic steps x 64 samples; the student steps on the last 64. rollout_batch_size: int = 320 + critic_steps_per_rollout: int = 5 + # 0 disables eval / checkpoints. eval_interval: int = 5 save_interval: int = 50 + # Colocated train + rollout GPUs; one node starts its own ray cluster. + num_nodes: int = 2 + num_gpus_per_node: int = 8 + # Below 16 GPUs the two 31B optimizers do not fit: keep params, grads and optimizer states in + # host memory (the optimizer steps on the CPU). + fsdp_cpu_offload: bool = False duration_seconds: float = 5.0 data_dir: str = "/root/datasets" # "teacher" or "fasth3": render the eval prompts with that model instead of training. @@ -169,6 +186,8 @@ def execute(args: ScriptArgs, prompt_dir: str) -> None: "--n-samples-per-eval-prompt 1 " f"--save-eval-media-dir {run_dir}/eval_media " ) + if not args.reference and args.eval_interval <= 0: + eval_args = "" # Every eval video; training rollouts carry no media, since --rm-type none skips their decode. wandb_args = U.get_default_wandb_args( @@ -189,13 +208,14 @@ def execute(args: ScriptArgs, prompt_dir: str) -> None: "--update-weight-buffer-size 4294967296 " ) + num_gpus = args.num_nodes * args.num_gpus_per_node topology_args = ( - "--actor-num-nodes 2 " - "--actor-num-gpus-per-node 8 " - "--num-gpus-per-node 8 " - "--rollout-num-gpus 16 " + f"--actor-num-nodes {args.num_nodes} " + f"--actor-num-gpus-per-node {args.num_gpus_per_node} " + f"--num-gpus-per-node {args.num_gpus_per_node} " + f"--rollout-num-gpus {num_gpus} " "--rollout-num-gpus-per-engine 2 " - "--rollout-parser-num-workers 16 " + f"--rollout-parser-num-workers {num_gpus} " "--colocate " # H3 denoising blocks the engine's event loop for tens of seconds per sample. "--rollout-health-check-interval 60 " @@ -219,16 +239,17 @@ def execute(args: ScriptArgs, prompt_dir: str) -> None: f"--diffusion-eval-num-steps {eval_steps} " ) else: + save_args = f"--save {run_dir}/ckpt --save-interval {args.save_interval} " if args.save_interval > 0 else "" + offload_args = "--fsdp-cpu-offload --teacher-cpu-offload " if args.fsdp_cpu_offload else "" mode_args = ( f"--hf-checkpoint {MODEL} " - f"--save {run_dir}/ckpt " - f"--save-interval {args.save_interval} " + f"{save_args}" f"--num-rollout {args.num_rollout} " - f"--eval-interval {args.eval_interval} " + f"{f'--eval-interval {args.eval_interval} ' if args.eval_interval > 0 else ''}" "--loss-type dmd2 " f"--teacher-load {MODEL} " "--dmd2-teacher-guidance-scale 1.0 " - "--dmd2-critic-steps-per-rollout 5 " + f"--dmd2-critic-steps-per-rollout {args.critic_steps_per_rollout} " "--dmd2-score-sigma-range 0.001 0.999 " "--dmd2-critic-loss-space x0 " "--fsdp-flow-shift visual=5.0 " @@ -242,6 +263,7 @@ def execute(args: ScriptArgs, prompt_dir: str) -> None: "--fsdp-reduce-dtype fp32 " "--diffusion-forward-dtype bf16 " "--gradient-checkpointing " + f"{offload_args}" ) U.execute_train( @@ -249,7 +271,7 @@ def execute(args: ScriptArgs, prompt_dir: str) -> None: f"{mode_args} {rollout_args} {diffusion_args} {eval_args} {wandb_args} {sglang_args} " f"{topology_args} {args.extra_args}" ), - num_gpus_per_node=8, + num_gpus_per_node=args.num_gpus_per_node, config=args, extra_env_vars={"PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True"}, ) diff --git a/tests/e2e/short/test_h3_t2va_dmd2_2xGPU.py b/tests/e2e/short/test_h3_t2va_dmd2_2xGPU.py new file mode 100644 index 000000000..5ba92f885 --- /dev/null +++ b/tests/e2e/short/test_h3_t2va_dmd2_2xGPU.py @@ -0,0 +1,54 @@ +"""E2E: MiniMax H3 t2va 4-step DMD2 (data-free), 2-GPU colocate (FSDP DP=2 over the +full-parameter student, critic and teacher, one tp2 sglang rollout engine, no reward), +2 rollouts of 4 prompts: 2 critic steps of 2 samples, then 1 student step on the last 2 +— runs the recipe script itself with its single-node knobs and checks its metric series +against the registered standard (tests/ci/fixtures/e2e_standards/). The three 31B models +do not fit two GPUs with their optimizers, so the recipe keeps parameters, gradients and +optimizer states in host memory (--fsdp-cpu-offload, about 1.1 TB) and steps on the CPU; +the master stays fp32, as H3's fp32-pinned modules rule out a bf16 master for +full-parameter training. Runs with --deterministic-mode, so every metric is compared +strictly, bit for bit. The only e2e exercising the multi-trainer-group driver, the +critic -> actor hand-off and the rollout stopped at a random step. Most of its time is the +three 62 GB checkpoints materializing into pinned host shards and the CPU optimizer steps, +so est_time lifts run_suite's 1800 s per-file cap (effective timeout = 1.25 x est_time).""" + +from tests.ci.e2e_metrics_registry import register_e2e_ci + +register_e2e_ci( + est_time=3300, + suite="stage-c-3-gpu-h200", + labels=["e2e"], + script="scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py", + args=[ + "--num-nodes", + "1", + "--num-gpus-per-node", + "2", + "--num-rollout", + "2", + "--rollout-batch-size", + "4", + "--critic-steps-per-rollout", + "2", + "--eval-interval", + "0", + "--save-interval", + "0", + "--duration-seconds", + "4", + "--fsdp-cpu-offload", + "--extra-args", + "--deterministic-mode", + ], + metrics=[ + "train/critic-loss", + "train/critic-grad_norm", + "train/grad_norm", + "train/dmd2_grad_abs_mean", + "train/dmd2_score_gap_abs_mean", + "train/dmd2_teacher_dist_abs_mean", + "train/dmd2_x0_mean", + "train/dmd2_x0_std", + "train/x0_mean_abs_diff", + ], +) From daff1b5340cafea00416f77c7c14cf766a19224e Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Tue, 10 Nov 2026 12:36:42 +0000 Subject: [PATCH 28/33] test(e2e): record the H3 DMD2 standard on CI and name the test as a proxy The standard comes from record-e2e-standards.yml on the 3gpu runner (run 42809959116, sglang zhihengy/sglang:dmd2/h3-dmd2-e2e), not from a local run. The test is renamed to the 16xGPU_single_node_2xGPU_proxy form the wan22 and krea2 proxies use, since it runs the 16-GPU recipe shrunk to two GPUs. Co-Authored-By: Claude Mythos 5.1 --- docs/models/h3/h3.md | 2 +- ...a_dmd2_16xGPU_single_node_2xGPU_proxy.json | 114 ++++++++++++++++++ ...va_dmd2_16xGPU_single_node_2xGPU_proxy.py} | 0 3 files changed, 115 insertions(+), 1 deletion(-) create mode 100644 tests/ci/fixtures/e2e_standards/test_h3_t2va_dmd2_16xGPU_single_node_2xGPU_proxy.json rename tests/e2e/short/{test_h3_t2va_dmd2_2xGPU.py => test_h3_t2va_dmd2_16xGPU_single_node_2xGPU_proxy.py} (100%) diff --git a/docs/models/h3/h3.md b/docs/models/h3/h3.md index 9b68bd168..64ae4cb6f 100644 --- a/docs/models/h3/h3.md +++ b/docs/models/h3/h3.md @@ -81,7 +81,7 @@ MILES_SCRIPT_EXTERNAL_RAY=1 python3 scripts/run_diffusion_dmd2_h3_t2va_16gpu_mul MILES_SCRIPT_EXTERNAL_RAY=1 python3 scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py --reference fasth3 ``` -The same script runs on one node for smoke runs; `tests/e2e/short/test_h3_t2va_dmd2_2xGPU.py` runs +The same script runs on one node for smoke runs; `tests/e2e/short/test_h3_t2va_dmd2_16xGPU_single_node_2xGPU_proxy.py` runs this 2-GPU proxy in CI (2 rollouts of 4 prompts, 2 critic steps, no eval or checkpoints). Below 16 GPUs the two 31B optimizers do not fit next to the models, so `--fsdp-cpu-offload` keeps parameters, gradients and optimizer states in host memory (about 1.1 TB; the optimizer steps on the diff --git a/tests/ci/fixtures/e2e_standards/test_h3_t2va_dmd2_16xGPU_single_node_2xGPU_proxy.json b/tests/ci/fixtures/e2e_standards/test_h3_t2va_dmd2_16xGPU_single_node_2xGPU_proxy.json new file mode 100644 index 000000000..a5c66d283 --- /dev/null +++ b/tests/ci/fixtures/e2e_standards/test_h3_t2va_dmd2_16xGPU_single_node_2xGPU_proxy.json @@ -0,0 +1,114 @@ +{ + "meta": { + "commit": "d4f042a97999c118314acd9f14ff17f97945875d", + "source": "test_h3_t2va_dmd2_16xGPU_single_node_2xGPU_proxy.py" + }, + "metrics": { + "train/critic-grad_norm": [ + [ + 1.0, + 0.7785962820053101 + ], + [ + 2.0, + 14.073819160461426 + ], + [ + 3.0, + 0.4356299638748169 + ], + [ + 4.0, + 1.8565646409988403 + ] + ], + "train/critic-loss": [ + [ + 1.0, + 0.10361059755086899 + ], + [ + 2.0, + 0.35569540970027447 + ], + [ + 3.0, + 0.043129388242959976 + ], + [ + 4.0, + 0.8326296955347061 + ] + ], + "train/dmd2_grad_abs_mean": [ + [ + 1.0, + 0.091581080108881 + ], + [ + 2.0, + 0.02208035346120596 + ] + ], + "train/dmd2_score_gap_abs_mean": [ + [ + 1.0, + 0.04178251465782523 + ], + [ + 2.0, + 0.018634567502886057 + ] + ], + "train/dmd2_teacher_dist_abs_mean": [ + [ + 1.0, + 0.39523235708475113 + ], + [ + 2.0, + 0.8179385364055634 + ] + ], + "train/dmd2_x0_mean": [ + [ + 1.0, + 0.056482404470443726 + ], + [ + 2.0, + -0.15674839541316032 + ] + ], + "train/dmd2_x0_std": [ + [ + 1.0, + 1.0739970207214355 + ], + [ + 2.0, + 2.475274920463562 + ] + ], + "train/grad_norm": [ + [ + 1.0, + 0.1290770024061203 + ], + [ + 2.0, + 0.21534393727779388 + ] + ], + "train/x0_mean_abs_diff": [ + [ + 1.0, + 0.0606351857462888 + ], + [ + 2.0, + 0.3335043992945757 + ] + ] + } +} diff --git a/tests/e2e/short/test_h3_t2va_dmd2_2xGPU.py b/tests/e2e/short/test_h3_t2va_dmd2_16xGPU_single_node_2xGPU_proxy.py similarity index 100% rename from tests/e2e/short/test_h3_t2va_dmd2_2xGPU.py rename to tests/e2e/short/test_h3_t2va_dmd2_16xGPU_single_node_2xGPU_proxy.py From 5c9da326d5cfd9d74861aa0a2e3c6f436bc8f7db Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Wed, 11 Nov 2026 14:41:22 +0000 Subject: [PATCH 29/33] test(e2e): re-record the H3 DMD2 standard on sglang-miles record-e2e-standards.yml run 43032161294 on the 3gpu runner, this branch at daff1b53 on sglang-miles 47930723 (the tip with sgl-project/sglang#49440 and #49143, so no ci-sglang-pr override). All 22 metric points match the two records on the previous combo branch bit for bit; only meta.commit moves. Co-Authored-By: Claude Mythos 5.1 --- .../test_h3_t2va_dmd2_16xGPU_single_node_2xGPU_proxy.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/ci/fixtures/e2e_standards/test_h3_t2va_dmd2_16xGPU_single_node_2xGPU_proxy.json b/tests/ci/fixtures/e2e_standards/test_h3_t2va_dmd2_16xGPU_single_node_2xGPU_proxy.json index a5c66d283..e60ab92cd 100644 --- a/tests/ci/fixtures/e2e_standards/test_h3_t2va_dmd2_16xGPU_single_node_2xGPU_proxy.json +++ b/tests/ci/fixtures/e2e_standards/test_h3_t2va_dmd2_16xGPU_single_node_2xGPU_proxy.json @@ -1,6 +1,6 @@ { "meta": { - "commit": "d4f042a97999c118314acd9f14ff17f97945875d", + "commit": "daff1b5340cafea00416f77c7c14cf766a19224e", "source": "test_h3_t2va_dmd2_16xGPU_single_node_2xGPU_proxy.py" }, "metrics": { From 439990e5e86b6d6bac94a9ac2d0e154e690ff26e Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:02:46 +0000 Subject: [PATCH 30/33] test(e2e): run the H3 DMD2 proxy with LoRA adapters instead of CPU offload The full-parameter 2-GPU proxy keeps about 1.6 TB in host memory and Ray's memory monitor kills it whenever another e2e shares the CI node. The recipe script gets --lora: the student and the critic train LoRA adapters over frozen bf16 bases (about 112 GB per GPU, about 530 GB of host memory), and the e2e test uses it. The 16-GPU recipe stays full-parameter, and --fsdp-cpu-offload still runs it on fewer GPUs. --loss-type dmd2 now accepts --use-lora. --- docs/models/h3/h3.md | 19 +++++++----- miles/utils/arguments.py | 4 +-- ..._diffusion_dmd2_h3_t2va_16gpu_multinode.py | 30 +++++++++++++------ ...2va_dmd2_16xGPU_single_node_2xGPU_proxy.py | 28 ++++++++--------- tests/fast/utils/test_dmd2_arguments.py | 3 +- 5 files changed, 49 insertions(+), 35 deletions(-) diff --git a/docs/models/h3/h3.md b/docs/models/h3/h3.md index 64ae4cb6f..8485ae84c 100644 --- a/docs/models/h3/h3.md +++ b/docs/models/h3/h3.md @@ -81,17 +81,22 @@ MILES_SCRIPT_EXTERNAL_RAY=1 python3 scripts/run_diffusion_dmd2_h3_t2va_16gpu_mul MILES_SCRIPT_EXTERNAL_RAY=1 python3 scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py --reference fasth3 ``` -The same script runs on one node for smoke runs; `tests/e2e/short/test_h3_t2va_dmd2_16xGPU_single_node_2xGPU_proxy.py` runs -this 2-GPU proxy in CI (2 rollouts of 4 prompts, 2 critic steps, no eval or checkpoints). Below -16 GPUs the two 31B optimizers do not fit next to the models, so `--fsdp-cpu-offload` keeps -parameters, gradients and optimizer states in host memory (about 1.1 TB; the optimizer steps on the -CPU). The master stays fp32: H3 pins proj_in / time_embedder / proj_out to fp32, and FSDP2 wants one -original dtype across a group's trainable parameters. +The same script runs on one node for smoke runs. Below 16 GPUs the two 31B optimizers do not fit +next to the models, so pick one of: + +- `--lora`: the student and the critic train LoRA adapters (rank 64, lr 1e-4) over frozen bf16 + bases, all in GPU memory. `tests/e2e/short/test_h3_t2va_dmd2_16xGPU_single_node_2xGPU_proxy.py` + runs this on 2 GPUs in CI (2 rollouts of 4 prompts, 2 critic steps, no eval or checkpoints); it + is not a tuned recipe. +- `--fsdp-cpu-offload`: the full-parameter recipe with parameters, gradients and optimizer states + in host memory (about 1.6 TB with the engine; the optimizer steps on the CPU). The master stays + fp32: H3 pins proj_in / time_embedder / proj_out to fp32, and FSDP2 wants one original dtype + across a group's trainable parameters. ```bash python3 scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py --num-nodes 1 --num-gpus-per-node 2 \ --rollout-batch-size 4 --critic-steps-per-rollout 2 --num-rollout 2 --eval-interval 0 \ - --save-interval 0 --fsdp-cpu-offload + --save-interval 0 --lora ``` What to watch: diff --git a/miles/utils/arguments.py b/miles/utils/arguments.py index ec78f3686..eb48351e9 100644 --- a/miles/utils/arguments.py +++ b/miles/utils/arguments.py @@ -2149,9 +2149,9 @@ def validate_dmd2_args(args) -> None: "--loss-type dmd2 samples the student unguided; set --diffusion-guidance-scale 1.0 " "and drop --diffusion-true-cfg-scale" ) - if args.use_lora or args.teacher_lora_adapter_paths is not None: + if args.teacher_lora_adapter_paths is not None: raise ValueError( - "--loss-type dmd2 trains the full student and critic; drop --use-lora and --teacher-lora-adapter-path" + "--loss-type dmd2 takes its teacher from --teacher-load alone; drop --teacher-lora-adapter-path" ) if args.ref_mode != "none": raise ValueError("--loss-type dmd2 uses no reference model; drop --ref-mode and --diffusion-kl-beta") diff --git a/scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py b/scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py index b97892f75..5f04dd7f9 100644 --- a/scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py +++ b/scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py @@ -36,13 +36,16 @@ MILES_SCRIPT_EXTERNAL_RAY=1 python3 scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py Single node, for smoke runs and the e2e CI: the script starts its own ray cluster. Two GPUs hold the -rollout engine (tp2) and FSDP DP=2 over the student, the critic and the teacher only with their -parameters, gradients and optimizer states in host memory (--fsdp-cpu-offload; about 1.1 TB). The -master stays fp32: H3 keeps proj_in / time_embedder / proj_out in fp32, and FSDP2 wants one original -dtype across a group's trainable parameters, which a bf16 master would break for full-parameter training. +rollout engine (tp2) and FSDP DP=2 over the student, the critic and the teacher in one of two ways: + --lora the student and the critic train LoRA adapters (rank 64, lr 1e-4) over frozen + bf16 bases, all in GPU memory; what the e2e CI runs, not a tuned recipe; + --fsdp-cpu-offload the full-parameter recipe with its parameters, gradients and optimizer states + in host memory (about 1.6 TB with the engine). The master stays fp32: H3 keeps + proj_in / time_embedder / proj_out in fp32, and FSDP2 wants one original dtype + across a group's trainable parameters. python3 scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py --num-nodes 1 --num-gpus-per-node 2 \ --rollout-batch-size 4 --critic-steps-per-rollout 2 --num-rollout 2 --eval-interval 0 \ - --save-interval 0 --fsdp-cpu-offload + --save-interval 0 --lora """ import hashlib @@ -101,6 +104,8 @@ class ScriptArgs(U.ExecuteTrainConfig): # Below 16 GPUs the two 31B optimizers do not fit: keep params, grads and optimizer states in # host memory (the optimizer steps on the CPU). fsdp_cpu_offload: bool = False + # Or train LoRA adapters of the student and the critic over frozen bf16 bases. + lora: bool = False duration_seconds: float = 5.0 data_dir: str = "/root/datasets" # "teacher" or "fasth3": render the eval prompts with that model instead of training. @@ -241,6 +246,16 @@ def execute(args: ScriptArgs, prompt_dir: str) -> None: else: save_args = f"--save {run_dir}/ckpt --save-interval {args.save_interval} " if args.save_interval > 0 else "" offload_args = "--fsdp-cpu-offload --teacher-cpu-offload " if args.fsdp_cpu_offload else "" + if args.lora: + # The adapters leave H3's fp32-pinned modules frozen, so the master can be bf16. + params_args = ( + "--use-lora --lora-ipc-weight-sync --lora-rank 64 --lora-alpha 128 " + "--sglang-lora-merge-mode merge " + "--lr 1e-4 --critic-lr 1e-4 " + "--fsdp-master-dtype bf16 --fsdp-reduce-dtype bf16 " + ) + else: + params_args = "--lr 2e-6 --critic-lr 2e-6 --fsdp-master-dtype fp32 --fsdp-reduce-dtype fp32 " mode_args = ( f"--hf-checkpoint {MODEL} " f"{save_args}" @@ -255,12 +270,9 @@ def execute(args: ScriptArgs, prompt_dir: str) -> None: "--fsdp-flow-shift visual=5.0 " "--diffusion-step-strategy-path miles.rollout.step_strategy_hub.stop_at_random_step " "--diffusion-sde-type ode " - "--lr 2e-6 " - "--critic-lr 2e-6 " + f"{params_args}" "--weight-decay 0.01 " "--train-backend fsdp " - "--fsdp-master-dtype fp32 " - "--fsdp-reduce-dtype fp32 " "--diffusion-forward-dtype bf16 " "--gradient-checkpointing " f"{offload_args}" diff --git a/tests/e2e/short/test_h3_t2va_dmd2_16xGPU_single_node_2xGPU_proxy.py b/tests/e2e/short/test_h3_t2va_dmd2_16xGPU_single_node_2xGPU_proxy.py index 5ba92f885..7e8c16f1d 100644 --- a/tests/e2e/short/test_h3_t2va_dmd2_16xGPU_single_node_2xGPU_proxy.py +++ b/tests/e2e/short/test_h3_t2va_dmd2_16xGPU_single_node_2xGPU_proxy.py @@ -1,21 +1,19 @@ -"""E2E: MiniMax H3 t2va 4-step DMD2 (data-free), 2-GPU colocate (FSDP DP=2 over the -full-parameter student, critic and teacher, one tp2 sglang rollout engine, no reward), -2 rollouts of 4 prompts: 2 critic steps of 2 samples, then 1 student step on the last 2 -— runs the recipe script itself with its single-node knobs and checks its metric series -against the registered standard (tests/ci/fixtures/e2e_standards/). The three 31B models -do not fit two GPUs with their optimizers, so the recipe keeps parameters, gradients and -optimizer states in host memory (--fsdp-cpu-offload, about 1.1 TB) and steps on the CPU; -the master stays fp32, as H3's fp32-pinned modules rule out a bf16 master for -full-parameter training. Runs with --deterministic-mode, so every metric is compared -strictly, bit for bit. The only e2e exercising the multi-trainer-group driver, the -critic -> actor hand-off and the rollout stopped at a random step. Most of its time is the -three 62 GB checkpoints materializing into pinned host shards and the CPU optimizer steps, -so est_time lifts run_suite's 1800 s per-file cap (effective timeout = 1.25 x est_time).""" +"""E2E: MiniMax H3 t2va 4-step DMD2 (data-free), 2-GPU colocate (FSDP DP=2 over the student, +the critic and the teacher, one tp2 sglang rollout engine, no reward), 2 rollouts of 4 +prompts: 2 critic steps of 2 samples, then 1 student step on the last 2 — runs the recipe +script itself with its single-node knobs and checks its metric series against the registered +standard (tests/ci/fixtures/e2e_standards/). Two GPUs cannot hold the full-parameter recipe, +and its CPU-offloaded form (--fsdp-cpu-offload, about 1.6 TB of host memory) does not fit the +shared CI node next to another e2e, so the student and the critic train LoRA adapters over +frozen bf16 bases here (--lora, about 112 GB per GPU at the critic step). Runs with +--deterministic-mode, so every metric is compared strictly, bit for bit. The only e2e +exercising the multi-trainer-group driver, the critic -> actor hand-off and the rollout +stopped at a random step.""" from tests.ci.e2e_metrics_registry import register_e2e_ci register_e2e_ci( - est_time=3300, + est_time=1200, suite="stage-c-3-gpu-h200", labels=["e2e"], script="scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py", @@ -36,7 +34,7 @@ "0", "--duration-seconds", "4", - "--fsdp-cpu-offload", + "--lora", "--extra-args", "--deterministic-mode", ], diff --git a/tests/fast/utils/test_dmd2_arguments.py b/tests/fast/utils/test_dmd2_arguments.py index fb0ac64fc..e9d34ed7f 100644 --- a/tests/fast/utils/test_dmd2_arguments.py +++ b/tests/fast/utils/test_dmd2_arguments.py @@ -125,8 +125,7 @@ def test_valid_dmd2_args_pass_unchanged(): ({"dmd2_score_sigma_range": [0.5, 1.5]}, "0 <= MIN < MAX <= 1"), ({"diffusion_guidance_scale": 4.5}, "samples the student unguided"), ({"diffusion_true_cfg_scale": 4.5}, "samples the student unguided"), - ({"use_lora": True}, "drop --use-lora"), - ({"teacher_lora_adapter_paths": ["teacher-adapter"]}, "drop --use-lora and --teacher-lora-adapter-path"), + ({"teacher_lora_adapter_paths": ["teacher-adapter"]}, "drop --teacher-lora-adapter-path"), ({"ref_mode": "ref"}, "uses no reference model"), ({"diffusion_recompute_old_log_prob": True}, "not DMD2"), ({"num_steps_per_rollout": 2}, "one actor step per rollout"), From bc22ebe6fc0c8d24e372b5b158bb4c609a583425 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:18:28 +0000 Subject: [PATCH 31/33] test(e2e): re-record the H3 DMD2 standard for the LoRA proxy Recorded on the 3gpu CI runner by run 45285320503 at 439990e5. --- ...a_dmd2_16xGPU_single_node_2xGPU_proxy.json | 36 +++++++++---------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/tests/ci/fixtures/e2e_standards/test_h3_t2va_dmd2_16xGPU_single_node_2xGPU_proxy.json b/tests/ci/fixtures/e2e_standards/test_h3_t2va_dmd2_16xGPU_single_node_2xGPU_proxy.json index e60ab92cd..163dfc516 100644 --- a/tests/ci/fixtures/e2e_standards/test_h3_t2va_dmd2_16xGPU_single_node_2xGPU_proxy.json +++ b/tests/ci/fixtures/e2e_standards/test_h3_t2va_dmd2_16xGPU_single_node_2xGPU_proxy.json @@ -1,25 +1,25 @@ { "meta": { - "commit": "daff1b5340cafea00416f77c7c14cf766a19224e", + "commit": "439990e5e86b6d6bac94a9ac2d0e154e690ff26e", "source": "test_h3_t2va_dmd2_16xGPU_single_node_2xGPU_proxy.py" }, "metrics": { "train/critic-grad_norm": [ [ 1.0, - 0.7785962820053101 + 0.06304825842380524 ], [ 2.0, - 14.073819160461426 + 1.4389699697494507 ], [ 3.0, - 0.4356299638748169 + 0.04073259234428406 ], [ 4.0, - 1.8565646409988403 + 0.30865904688835144 ] ], "train/critic-loss": [ @@ -29,35 +29,35 @@ ], [ 2.0, - 0.35569540970027447 + 0.3423595726490021 ], [ 3.0, - 0.043129388242959976 + 0.04162454791367054 ], [ 4.0, - 0.8326296955347061 + 0.8172207176685333 ] ], "train/dmd2_grad_abs_mean": [ [ 1.0, - 0.091581080108881 + 0.08365654572844505 ], [ 2.0, - 0.02208035346120596 + 0.027618293650448322 ] ], "train/dmd2_score_gap_abs_mean": [ [ 1.0, - 0.04178251465782523 + 0.03811744134873152 ], [ 2.0, - 0.018634567502886057 + 0.021260653622448444 ] ], "train/dmd2_teacher_dist_abs_mean": [ @@ -67,7 +67,7 @@ ], [ 2.0, - 0.8179385364055634 + 0.83000248670578 ] ], "train/dmd2_x0_mean": [ @@ -77,7 +77,7 @@ ], [ 2.0, - -0.15674839541316032 + -0.15415865182876587 ] ], "train/dmd2_x0_std": [ @@ -87,17 +87,17 @@ ], [ 2.0, - 2.475274920463562 + 2.4941294193267822 ] ], "train/grad_norm": [ [ 1.0, - 0.1290770024061203 + 0.009701848961412907 ], [ 2.0, - 0.21534393727779388 + 0.04545477405190468 ] ], "train/x0_mean_abs_diff": [ @@ -107,7 +107,7 @@ ], [ 2.0, - 0.3335043992945757 + 0.33430661600102823 ] ] } From 196f7699253ef1f0a55c1c6146af81d4edf21fdc Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:19:03 +0000 Subject: [PATCH 32/33] docs(dmd2): state the LoRA proxy's GPU memory as the trainer reports it --- docs/models/h3/h3.md | 2 +- scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py | 2 +- .../short/test_h3_t2va_dmd2_16xGPU_single_node_2xGPU_proxy.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/models/h3/h3.md b/docs/models/h3/h3.md index 8485ae84c..56a3c29cb 100644 --- a/docs/models/h3/h3.md +++ b/docs/models/h3/h3.md @@ -85,7 +85,7 @@ The same script runs on one node for smoke runs. Below 16 GPUs the two 31B optim next to the models, so pick one of: - `--lora`: the student and the critic train LoRA adapters (rank 64, lr 1e-4) over frozen bf16 - bases, all in GPU memory. `tests/e2e/short/test_h3_t2va_dmd2_16xGPU_single_node_2xGPU_proxy.py` + bases, with no CPU offload. `tests/e2e/short/test_h3_t2va_dmd2_16xGPU_single_node_2xGPU_proxy.py` runs this on 2 GPUs in CI (2 rollouts of 4 prompts, 2 critic steps, no eval or checkpoints); it is not a tuned recipe. - `--fsdp-cpu-offload`: the full-parameter recipe with parameters, gradients and optimizer states diff --git a/scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py b/scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py index 5f04dd7f9..ee42f954d 100644 --- a/scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py +++ b/scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py @@ -38,7 +38,7 @@ Single node, for smoke runs and the e2e CI: the script starts its own ray cluster. Two GPUs hold the rollout engine (tp2) and FSDP DP=2 over the student, the critic and the teacher in one of two ways: --lora the student and the critic train LoRA adapters (rank 64, lr 1e-4) over frozen - bf16 bases, all in GPU memory; what the e2e CI runs, not a tuned recipe; + bf16 bases, with no CPU offload; what the e2e CI runs, not a tuned recipe; --fsdp-cpu-offload the full-parameter recipe with its parameters, gradients and optimizer states in host memory (about 1.6 TB with the engine). The master stays fp32: H3 keeps proj_in / time_embedder / proj_out in fp32, and FSDP2 wants one original dtype diff --git a/tests/e2e/short/test_h3_t2va_dmd2_16xGPU_single_node_2xGPU_proxy.py b/tests/e2e/short/test_h3_t2va_dmd2_16xGPU_single_node_2xGPU_proxy.py index 7e8c16f1d..dd24c5b5c 100644 --- a/tests/e2e/short/test_h3_t2va_dmd2_16xGPU_single_node_2xGPU_proxy.py +++ b/tests/e2e/short/test_h3_t2va_dmd2_16xGPU_single_node_2xGPU_proxy.py @@ -5,7 +5,7 @@ standard (tests/ci/fixtures/e2e_standards/). Two GPUs cannot hold the full-parameter recipe, and its CPU-offloaded form (--fsdp-cpu-offload, about 1.6 TB of host memory) does not fit the shared CI node next to another e2e, so the student and the critic train LoRA adapters over -frozen bf16 bases here (--lora, about 112 GB per GPU at the critic step). Runs with +frozen bf16 bases here (--lora, about 110 GB per GPU at the critic step). Runs with --deterministic-mode, so every metric is compared strictly, bit for bit. The only e2e exercising the multi-trainer-group driver, the critic -> actor hand-off and the rollout stopped at a random step.""" From 5b99cf45be0f15f6129599adfbad15a9bee26d8f Mon Sep 17 00:00:00 2001 From: rockdu Date: Tue, 24 Nov 2026 22:21:52 -0800 Subject: [PATCH 33/33] docs(h3): drop the single-node smoke section from the model page The model page carries recipes meant to be run; the single-node --lora / --fsdp-cpu-offload modes are smoke configurations for CI and development, documented where they live: the recipe script's docstring and the e2e test. The section also copied the docstring word for word. --- docs/models/h3/h3.md | 18 ------------------ 1 file changed, 18 deletions(-) diff --git a/docs/models/h3/h3.md b/docs/models/h3/h3.md index 56a3c29cb..361e0ebf5 100644 --- a/docs/models/h3/h3.md +++ b/docs/models/h3/h3.md @@ -81,24 +81,6 @@ MILES_SCRIPT_EXTERNAL_RAY=1 python3 scripts/run_diffusion_dmd2_h3_t2va_16gpu_mul MILES_SCRIPT_EXTERNAL_RAY=1 python3 scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py --reference fasth3 ``` -The same script runs on one node for smoke runs. Below 16 GPUs the two 31B optimizers do not fit -next to the models, so pick one of: - -- `--lora`: the student and the critic train LoRA adapters (rank 64, lr 1e-4) over frozen bf16 - bases, with no CPU offload. `tests/e2e/short/test_h3_t2va_dmd2_16xGPU_single_node_2xGPU_proxy.py` - runs this on 2 GPUs in CI (2 rollouts of 4 prompts, 2 critic steps, no eval or checkpoints); it - is not a tuned recipe. -- `--fsdp-cpu-offload`: the full-parameter recipe with parameters, gradients and optimizer states - in host memory (about 1.6 TB with the engine; the optimizer steps on the CPU). The master stays - fp32: H3 pins proj_in / time_embedder / proj_out to fp32, and FSDP2 wants one original dtype - across a group's trainable parameters. - -```bash -python3 scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py --num-nodes 1 --num-gpus-per-node 2 \ - --rollout-batch-size 4 --critic-steps-per-rollout 2 --num-rollout 2 --eval-interval 0 \ - --save-interval 0 --lora -``` - What to watch: | Signal | Where | Reading |