From 42c4a146fe82a8e7346ea369cb8328763da00a55 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Mon, 2 Nov 2026 10:13:35 +0000 Subject: [PATCH 1/7] fix(fsdp): make wake_up a no-op while the group is awake A group that trains and then scores in the same wake would wake twice, and waking a frozen model twice replaces its pinned host copies with its GPU parameters, so the next sleep would leave the teacher on the GPU. Co-Authored-By: Claude Mythos 5.1 --- miles/backends/fsdp_utils/actor.py | 6 +- .../backends/fsdp_utils/test_sleep_wake.py | 79 +++++++++++++++++++ 2 files changed, 84 insertions(+), 1 deletion(-) create mode 100644 tests/fast/backends/fsdp_utils/test_sleep_wake.py diff --git a/miles/backends/fsdp_utils/actor.py b/miles/backends/fsdp_utils/actor.py index b948f444c..cc6428afb 100644 --- a/miles/backends/fsdp_utils/actor.py +++ b/miles/backends/fsdp_utils/actor.py @@ -157,6 +157,7 @@ def init(self, args: Namespace, role: str, with_ref: bool = False) -> int: # ty ] # Reference and teacher weights never change, so each sleep points them back at the host copies kept at wake. self.frozen_parameter_host_copies_by_model = {model: {} for model in self.frozen_models_to_sleep} + self.asleep = False # Force a sync to ensure sharding is complete and old memory is freed. torch.cuda.synchronize() @@ -246,12 +247,14 @@ def sleep(self) -> None: if self.ema_optimizer is not None: move_optimizer(self.ema_optimizer, "cpu") clear_memory() + self.asleep = True dist.barrier(group=get_gloo_group()) print_memory("after sleep DiT") @timer def wake_up(self) -> None: - if not self.args.offload_train: + # Waking twice would point the frozen models' host copies at their GPU parameters. + if not self.args.offload_train or not self.asleep: return for model in self.actor_models_to_sleep: @@ -262,6 +265,7 @@ def wake_up(self) -> None: move_optimizer(self.optimizer, "cuda") if self.ema_optimizer is not None: move_optimizer(self.ema_optimizer, "cuda") + self.asleep = False dist.barrier(group=get_gloo_group()) print_memory("after wake_up DiT") diff --git a/tests/fast/backends/fsdp_utils/test_sleep_wake.py b/tests/fast/backends/fsdp_utils/test_sleep_wake.py new file mode 100644 index 000000000..b783cc787 --- /dev/null +++ b/tests/fast/backends/fsdp_utils/test_sleep_wake.py @@ -0,0 +1,79 @@ +"""wake_up moves a sleeping group's models and optimizers once; a second wake_up before sleep does nothing. + +Consecutive train or compute calls of one group skip the sleep in between, and waking a frozen model twice would replace its host +copies with its GPU parameters, so the next sleep would leave it on the GPU. +""" + +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 pathlib import Path +from types import SimpleNamespace + + +def _load_sleep_and_wake_up(moves): + 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" + ) + methods = [ + node for node in actor_class.body if isinstance(node, ast.FunctionDef) and node.name in ("sleep", "wake_up") + ] + namespace = dict( + timer=lambda fn: fn, + print_memory=lambda name: None, + clear_memory=lambda: None, + get_gloo_group=lambda: None, + dist=SimpleNamespace(barrier=lambda group: None), + move_model=lambda model, device: moves.append(("model", model, device)), + sleep_frozen_model=lambda model, host_copies: moves.append(("frozen", model, "cpu")), + wake_up_frozen_model=lambda model, host_copies: moves.append(("frozen", model, "cuda")), + move_optimizer=lambda optimizer, device: moves.append(("optimizer", optimizer, device)), + ) + exec(compile(ast.Module(body=methods, type_ignores=[]), str(path), "exec"), namespace) + return namespace["sleep"], namespace["wake_up"] + + +def _actor(): + return SimpleNamespace( + args=Namespace(offload_train=True, fsdp_cpu_offload=False), + actor_models_to_sleep=["student"], + frozen_models_to_sleep=["teacher"], + frozen_parameter_host_copies_by_model={"teacher": {}}, + optimizer=SimpleNamespace(zero_grad=lambda set_to_none: None), + ema_optimizer=None, + asleep=False, + ) + + +def test_wake_up_moves_once_until_the_next_sleep(): + moves = [] + sleep, wake_up = _load_sleep_and_wake_up(moves) + actor = _actor() + + sleep(actor) + wake_up(actor) + wake_up(actor) + sleep(actor) + + to_cpu = [("model", "student", "cpu"), ("frozen", "teacher", "cpu"), ("optimizer", actor.optimizer, "cpu")] + to_cuda = [("model", "student", "cuda"), ("frozen", "teacher", "cuda"), ("optimizer", actor.optimizer, "cuda")] + assert moves == to_cpu + to_cuda + to_cpu + assert actor.asleep + + +def test_wake_up_without_offload_does_nothing(): + moves = [] + _, wake_up = _load_sleep_and_wake_up(moves) + actor = _actor() + actor.args.offload_train = False + actor.asleep = True + + wake_up(actor) + + assert moves == [] From 448b6a1eebf0bec5fd5cd56c6062370eebce10fe Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Wed, 11 Nov 2026 10:32:26 +0000 Subject: [PATCH 2/7] feat(fsdp): train a range of the rollout's optimizer steps `train(..., optim_steps=(lo, hi))` runs windows lo..hi-1 of the rollout's micro-batch schedule with the micro-batch ids of the full run, so a range draws the same noise as the whole rollout would; a range outside the schedule, or one under --diffusion-recompute-old-log-prob, is rejected. The EMA steps once per rollout, by the call whose range ends at the last step. `RayTrainGroup.async_train` passes the range through. Co-Authored-By: Claude Mythos 5.1 --- miles/backends/fsdp_utils/actor.py | 54 ++++++++++---- miles/ray/actor_group.py | 7 +- .../fsdp_utils/test_train_input_hook.py | 21 ++++-- .../fsdp_utils/test_train_optim_steps.py | 74 +++++++++++++++++++ .../fsdp_utils/test_train_output_handoff.py | 17 +++-- tests/fast/rollout/test_async_training.py | 2 +- tests/fast/rollout/test_placement_group.py | 7 +- 7 files changed, 146 insertions(+), 36 deletions(-) create mode 100644 tests/fast/backends/fsdp_utils/test_train_optim_steps.py diff --git a/miles/backends/fsdp_utils/actor.py b/miles/backends/fsdp_utils/actor.py index cc6428afb..f5f13a4c5 100644 --- a/miles/backends/fsdp_utils/actor.py +++ b/miles/backends/fsdp_utils/actor.py @@ -325,7 +325,10 @@ def _log_metrics(self, rollout_id: int, log_dict: dict[str, float], step: int) - ) ) - def train(self, rollout_id: int, rollout_data_ref, external_data) -> Any: # type: ignore[override] + def train( # type: ignore[override] + self, rollout_id: int, rollout_data_ref, external_data, optim_steps: tuple[int, int] | None = None + ) -> Any: + """Train this rank's shard of the rollout: all of its optimizer steps, or the range ``optim_steps``.""" if self.args.offload_train: self.wake_up() @@ -337,9 +340,12 @@ def train(self, rollout_id: int, rollout_data_ref, external_data) -> Any: # typ materialize_stored_tensors(rollout_data["train_data"], store=self._output_store) 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 + rollout_id=rollout_id, rollout_data=rollout_data, external_data=external_data, optim_steps=optim_steps ) - if self.ema_optimizer is not None: + # The EMA moves once per rollout, after its last step, whichever call trains that step. + if self.ema_optimizer is not None and ( + optim_steps is None or optim_steps[1] == self.args.num_steps_per_rollout + ): self.ema_optimizer.step(self.global_step) train_metric_utils.log_perf_data_raw( @@ -351,26 +357,34 @@ def train(self, rollout_id: int, rollout_data_ref, external_data) -> Any: # typ # 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.""" - device = torch.device("cuda", torch.cuda.current_device()) - - train_pairs: list = rollout_data["train_data"] - if not train_pairs: - raise ValueError("rollout_data['train_data'] is empty") - - loss_ctx = DiffusionLossContext( + def _loss_context(self, rollout_id: int, external_data: dict[str, Any]) -> DiffusionLossContext: + return DiffusionLossContext( models=self.models, reference_models=self.reference_models, train_pipeline_config=self.train_pipeline_config, sde_backend=self.sde_backend, args=self.args, forward_dtype=self._forward_dtype, - device=device, + device=torch.device("cuda", torch.cuda.current_device()), rollout_id=rollout_id, dp_rank=self.parallel_state.dp_rank, external_data=external_data, ) + + def _train_core( + self, + rollout_id: int, + rollout_data, + external_data: dict[str, Any], + optim_steps: tuple[int, int] | None = None, + ) -> Any: + """Run the shared diffusion training loop; ``optim_steps`` limits it to a range of the rollout's steps.""" + train_pairs: list = rollout_data["train_data"] + if not train_pairs: + raise ValueError("rollout_data['train_data'] is empty") + + loss_ctx = self._loss_context(rollout_id, external_data) + device = loss_ctx.device 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 @@ -402,6 +416,14 @@ def _train_core(self, rollout_id: int, rollout_data, external_data: dict[str, An microbatch_schedule=microbatch_schedule, ) + step_lo, step_hi = (0, num_optim_steps_per_rollout) if optim_steps is None else optim_steps + if not 0 <= step_lo < step_hi <= num_optim_steps_per_rollout: + raise ValueError( + f"optim_steps={optim_steps} is not a range within the {num_optim_steps_per_rollout} steps" + ) + if optim_steps is not None and self.args.diffusion_recompute_old_log_prob: + raise ValueError("--diffusion-recompute-old-log-prob recomputes the whole rollout; no step range") + # ------------- 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(): @@ -432,8 +454,10 @@ def _train_core(self, rollout_id: int, rollout_data, external_data: dict[str, An # ------------- Forward / Backward ------------- with timer("actor_train"): - microbatch_id = 0 - for optim_step_idx, microbatch_ranges in enumerate(microbatch_schedule): + # The micro-batch ids of the full run, so a range draws the same noise as the whole rollout would. + microbatch_id = sum(len(microbatch_ranges) for microbatch_ranges in microbatch_schedule[:step_lo]) + for optim_step_idx in range(step_lo, step_hi): + microbatch_ranges = microbatch_schedule[optim_step_idx] self.optimizer.zero_grad(set_to_none=True) old_log_prob_from_new = self.args.diffusion_recompute_old_log_prob and optim_step_idx == 0 diff --git a/miles/ray/actor_group.py b/miles/ray/actor_group.py index 3cb749b3f..f99b066a5 100644 --- a/miles/ray/actor_group.py +++ b/miles/ray/actor_group.py @@ -100,12 +100,13 @@ 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, external_data=None): - """Do one rollout training; rank i receives rank i's output of each group in ``external_data``.""" + def async_train(self, rollout_id, rollout_data_ref, external_data=None, optim_steps=None): + """Train the rollout, or the range ``optim_steps`` of its optimizer steps; 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()} + rollout_id, rollout_data_ref, {role: refs[rank] for role, refs in external_data.items()}, optim_steps ) for rank, actor in enumerate(self._actor_handlers) ] 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 b01bf3384..25698ff0a 100644 --- a/tests/fast/backends/fsdp_utils/test_train_input_hook.py +++ b/tests/fast/backends/fsdp_utils/test_train_input_hook.py @@ -24,7 +24,6 @@ from types import SimpleNamespace from typing import Any -import pytest import torch from miles.backends.fsdp_utils.loss_hub.types import DiffusionLossContext @@ -56,7 +55,7 @@ def _load_train_core(): def _actor(train_input, train_output, forwarded, **args): lists = [] # the train_output_inputs object each forward received - return SimpleNamespace( + actor = SimpleNamespace( lists=lists, models={}, reference_models={}, @@ -86,11 +85,19 @@ def _actor(train_input, train_output, forwarded, **args): ), _log_metrics=lambda rollout_id, metrics, step: None, ) - - -@pytest.fixture(autouse=True) -def _cpu_device(monkeypatch): - monkeypatch.setattr(torch.cuda, "current_device", lambda: 0) + actor._loss_context = lambda rollout_id, external_data: DiffusionLossContext( + models=actor.models, + reference_models=actor.reference_models, + train_pipeline_config=None, + sde_backend=None, + args=actor.args, + forward_dtype=torch.float32, + device=torch.device("cpu"), + rollout_id=rollout_id, + dp_rank=0, + external_data=external_data, + ) + return actor def test_later_stages_see_the_preprocessed_pairs(): diff --git a/tests/fast/backends/fsdp_utils/test_train_optim_steps.py b/tests/fast/backends/fsdp_utils/test_train_optim_steps.py new file mode 100644 index 000000000..b07ef5b9e --- /dev/null +++ b/tests/fast/backends/fsdp_utils/test_train_optim_steps.py @@ -0,0 +1,74 @@ +"""A train call may cover a range of the rollout's optimizer steps; the rollout's EMA step follows its last step. + + train(optim_steps=(lo, hi)) ──► _train_core trains windows lo..hi-1 with the micro-batch ids of the full run + (the earlier windows' micro-batches are counted, not run) + a range outside the schedule, or one under --diffusion-recompute-old-log-prob ──► ValueError + ema_optimizer.step ──► once per rollout, by the call whose range ends at the last step (or trains them all) +""" + +from tests.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=5, suite="stage-a-cpu", labels=["fsdp"]) + +from types import SimpleNamespace + +import pytest +from tests.fast.backends.fsdp_utils.test_train_input_hook import _actor, _load_train_core +from tests.fast.backends.fsdp_utils.test_train_output_handoff import _load_methods + +from miles.utils.ray_utils import Box + + +def test_a_step_range_trains_those_steps_only(): + pairs = [{"sample_index": index} for index in range(6)] + forwarded = [] + actor = _actor(None, None, forwarded) + actor.args.num_steps_per_rollout = 3 + + _load_train_core()(actor, rollout_id=0, rollout_data={"train_data": pairs}, external_data={}, optim_steps=(1, 3)) + + # Windows 1 and 2: micro-batches 2..5, numbered as in the full run. + assert forwarded == [(index, index // 2, False, [pair]) for index, pair in enumerate(pairs)][2:] + assert actor.global_step == 2 + + +@pytest.mark.parametrize("optim_steps", [(1, 3), (1, 1), (-1, 1)]) +def test_a_step_range_outside_the_schedule_is_rejected(optim_steps): + pairs = [{"sample_index": index} for index in range(4)] + with pytest.raises(ValueError, match="not a range within the 2 steps"): + _load_train_core()( + _actor(None, None, []), + rollout_id=0, + rollout_data={"train_data": pairs}, + external_data={}, + optim_steps=optim_steps, + ) + + +def test_a_step_range_cannot_recompute_old_log_probs(): + pairs = [{"sample_index": index} for index in range(4)] + actor = _actor(None, None, [], diffusion_recompute_old_log_prob=True) + with pytest.raises(ValueError, match="no step range"): + _load_train_core()( + actor, rollout_id=0, rollout_data={"train_data": pairs}, external_data={}, optim_steps=(0, 1) + ) + + +@pytest.mark.parametrize( + ("optim_steps", "ema_steps"), + [(None, 1), ((0, 2), 0), ((2, 3), 1), ((0, 3), 1)], +) +def test_the_ema_steps_once_per_rollout_after_its_last_step(optim_steps, ema_steps): + namespace, store, put = _load_methods("train") + ema_calls = [] + actor = SimpleNamespace( + args=SimpleNamespace(offload_train=False, debug_rollout_only=False, num_steps_per_rollout=3), + ema_optimizer=SimpleNamespace(step=ema_calls.append), + global_step=7, + _train_core=lambda rollout_id, rollout_data, external_data, optim_steps: None, + parallel_state=SimpleNamespace(get_mesh=lambda name: SimpleNamespace(get_local_rank=lambda: 0)), + ) + + namespace["train"](actor, 0, [Box(put({"train_data": []}))], {}, optim_steps) + + assert ema_calls == [7] * ema_steps diff --git a/tests/fast/backends/fsdp_utils/test_train_output_handoff.py b/tests/fast/backends/fsdp_utils/test_train_output_handoff.py index 782bc02f2..765ffdd85 100644 --- a/tests/fast/backends/fsdp_utils/test_train_output_handoff.py +++ b/tests/fast/backends/fsdp_utils/test_train_output_handoff.py @@ -13,15 +13,17 @@ from miles.utils.ray_utils import Box -def _load_train(): +def _load_methods(*names): + """The named FSDPTrainRayActor methods, compiled with Ray, the timers and the perf log replaced.""" 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 = [] + methods = [node for node in actor_class.body if isinstance(node, ast.FunctionDef) and node.name in names] + for method in methods: + method.decorator_list = [] store = {} def put(value): @@ -38,15 +40,16 @@ def put(value): 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 + exec(compile(ast.Module(body=methods, type_ignores=[]), str(path), "exec"), namespace) + return namespace, store, put def test_train_unboxes_external_data_and_boxes_its_output(): - train, store, put = _load_train() + namespace, store, put = _load_methods("train") + train = namespace["train"] seen = {} - def train_core(rollout_id, rollout_data, external_data): + def train_core(rollout_id, rollout_data, external_data, optim_steps=None): seen.update(rollout_data=rollout_data, external_data=external_data) return {"scores": [rollout_id]} diff --git a/tests/fast/rollout/test_async_training.py b/tests/fast/rollout/test_async_training.py index 26d44c2e4..49c2cbd74 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, external_data): + def _train_core(self, rollout_id, rollout_data, external_data, optim_steps=None): start = time.monotonic() with self.ema_optimizer.use_weights(self.model): reference = self.param.item() diff --git a/tests/fast/rollout/test_placement_group.py b/tests/fast/rollout/test_placement_group.py index 5e1e0cdb6..39650945e 100644 --- a/tests/fast/rollout/test_placement_group.py +++ b/tests/fast/rollout/test_placement_group.py @@ -121,7 +121,8 @@ def __init__(self, rank): 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"}), + (0, 7, "data", {"critic": "critic_0", "reward": "reward_0"}, None), + (1, 7, "data", {"critic": "critic_1", "reward": "reward_1"}, None), ] - assert group.async_train(7, "data") == [(0, 7, "data", {}), (1, 7, "data", {})] + assert group.async_train(7, "data") == [(0, 7, "data", {}, None), (1, 7, "data", {}, None)] + assert group.async_train(7, "data", optim_steps=(1, 3)) == [(0, 7, "data", {}, (1, 3)), (1, 7, "data", {}, (1, 3))] From 65a9812382d1c42f7bca76ec1076867551433712 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Wed, 11 Nov 2026 10:35:42 +0000 Subject: [PATCH 3/7] feat(fsdp): run a hook set forward-only over a rank's rollout shard `FSDPTrainRayActor.compute(rollout_id, rollout_data_ref, external_data, hooks_key)` runs the loss hub's `(--loss-type, hooks_key)` hooks without grad: their train-input selection, one forward per micro-batch through the trunk (`_forward_train_pair_batch` takes the hooks to run instead of the group's), numbered past the rollout's training micro-batches so no training forward shares a draw, then their train-output hook, boxed as train's output is. The models are resharded after; the optimizer, scheduler, EMA and step count stay. `RayTrainGroup.async_compute` dispatches it per rank like `async_train`. Co-Authored-By: Claude Mythos 5.1 --- miles/backends/fsdp_utils/actor.py | 78 +++++++++++++++- miles/ray/actor_group.py | 10 +++ .../backends/fsdp_utils/test_compute_hooks.py | 89 +++++++++++++++++++ .../fsdp_utils/test_reference_models.py | 31 +++++++ .../fsdp_utils/test_train_output_handoff.py | 31 ++++++- tests/fast/rollout/test_placement_group.py | 5 ++ 6 files changed, 239 insertions(+), 5 deletions(-) create mode 100644 tests/fast/backends/fsdp_utils/test_compute_hooks.py diff --git a/miles/backends/fsdp_utils/actor.py b/miles/backends/fsdp_utils/actor.py index f5f13a4c5..c7023de88 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, get_loss_hooks +from .loss_hub import DiffusionLossContext, LossHooks, get_loss_hooks from .lr_scheduler import get_lr_scheduler from .metrics import new_metric_buffer from .mixed_precision import parse_dtype_from_str @@ -357,6 +357,74 @@ def train( # type: ignore[override] # object store until the paired rank of a later group reads it. return Box(ray.put(train_output)) + def compute(self, rollout_id: int, rollout_data_ref, external_data, hooks_key: str) -> Any: + """Run the loss hub's ``(--loss-type, hooks_key)`` hooks forward-only on this rank's shard of the rollout. + + Their train-input selection, one no-grad forward per micro-batch and their train-output hook, whose return + value is boxed as train's is. Nothing trains: the optimizer, scheduler, EMA and step count stay. + """ + if self.args.offload_train: + self.wake_up() + + with inverse_timer("train_wait"), timer("compute"): + rollout_data = ray.get(rollout_data_ref[self.parallel_state.get_mesh("dp").get_local_rank()].inner) + if self.args.debug_rollout_only: + return + external_data = {role: ray.get(box.inner) for role, box in external_data.items()} + output = self._compute_core( + rollout_id=rollout_id, + rollout_data=rollout_data, + external_data=external_data, + hooks=get_loss_hooks(self.args, hooks_key), + ) + return Box(ray.put(output)) + + def _compute_core(self, rollout_id: int, rollout_data, external_data: dict[str, Any], hooks: LossHooks) -> Any: + """One no-grad forward per micro-batch of the pairs ``hooks.train_input`` keeps, then ``hooks.train_output``.""" + train_pairs: list = rollout_data["train_data"] + loss_ctx = self._loss_context(rollout_id, external_data) + if hooks.train_input is not None: + train_pairs = hooks.train_input(loss_ctx, train_pairs) + + micro_bs = self.args.micro_batch_size + num_optim_steps_per_rollout = self.args.num_steps_per_rollout + # Numbered past the training micro-batches of this rank's whole rollout, so no training forward shares a + # draw with these. + microbatch_schedule = build_microbatch_schedule( + num_pairs_per_optim_step=len(rollout_data["train_data"]) // num_optim_steps_per_rollout, + num_optim_steps_per_rollout=num_optim_steps_per_rollout, + micro_batch_size=micro_bs, + ) + microbatch_id = sum(len(microbatch_ranges) for microbatch_ranges in microbatch_schedule) + microbatch_ranges = [ + (pair_lo, min(pair_lo + micro_bs, len(train_pairs))) for pair_lo in range(0, len(train_pairs), micro_bs) + ] + train_output_inputs: list = [] + # The formula may emit metrics; nothing reduces or logs them here. + metrics = new_metric_buffer( + self.parallel_state.dp_group, loss_ctx.device, self.models, sigma_buckets=self.args.log_loss_sigma_bucket + ) + with torch.no_grad(): + legacy_pad_to_len = self._maybe_legacy_window_pad_len(train_pairs, microbatch_ranges) + for pair_lo, pair_hi in microbatch_ranges: + self._forward_train_pair_batch( + loss_ctx, + train_pairs[pair_lo:pair_hi], + microbatch_id=microbatch_id, + optim_step_idx=num_optim_steps_per_rollout - 1, + train_output_inputs=train_output_inputs, + metrics=metrics, + pad_to_len=legacy_pad_to_len, + hooks=hooks, + ) + microbatch_id += 1 + # A no-grad forward leaves FSDP's root parameters gathered; sleep must move the shards. + for model in (*self.models.values(), *self.reference_models.values()): + reshard_model(model) + if hooks.train_output is None: + return None + return hooks.train_output(loss_ctx, train_pairs, train_output_inputs) + def _loss_context(self, rollout_id: int, external_data: dict[str, Any]) -> DiffusionLossContext: return DiffusionLossContext( models=self.models, @@ -547,10 +615,12 @@ def _forward_train_pair_batch( pad_to_len: int | None = None, write_old_log_prob: bool = False, old_log_prob_from_new: bool = False, + hooks: LossHooks | None = None, ) -> torch.Tensor | None: """Run one prepared diffusion micro-batch: number ``microbatch_id`` of the rollout, in optimizer step - ``optim_step_idx``.""" - prepared = self.loss_hooks.prepare( + ``optim_step_idx``, through the group's hooks or ``hooks``.""" + hooks = self.loss_hooks if hooks is None else hooks + prepared = 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 @@ -628,7 +698,7 @@ def _compute_noise_pred( # PEFT re-enables adapter gradients on exit; reshard first so that lands on the shards, not gathered copies. reshard_model(prepared.model) - return self.loss_hooks.formula( + return hooks.formula( ctx, batch, prepared, diff --git a/miles/ray/actor_group.py b/miles/ray/actor_group.py index f99b066a5..3026bac08 100644 --- a/miles/ray/actor_group.py +++ b/miles/ray/actor_group.py @@ -111,6 +111,16 @@ def async_train(self, rollout_id, rollout_data_ref, external_data=None, optim_st for rank, actor in enumerate(self._actor_handlers) ] + def async_compute(self, rollout_id, rollout_data_ref, external_data, hooks_key): + """Run the loss hub's ``hooks_key`` hooks forward-only on each rank's shard; ``external_data`` as in + ``async_train``.""" + return [ + actor.compute.remote( + rollout_id, rollout_data_ref, {role: refs[rank] for role, refs in external_data.items()}, hooks_key + ) + for rank, actor in enumerate(self._actor_handlers) + ] + def save_model(self, rollout_id, force_sync=False): """Save actor model""" return ray.get([actor.save_model.remote(rollout_id, force_sync=force_sync) for actor in self._actor_handlers]) diff --git a/tests/fast/backends/fsdp_utils/test_compute_hooks.py b/tests/fast/backends/fsdp_utils/test_compute_hooks.py new file mode 100644 index 000000000..27643f52e --- /dev/null +++ b/tests/fast/backends/fsdp_utils/test_compute_hooks.py @@ -0,0 +1,89 @@ +"""_compute_core runs a hook set forward-only over the pairs its train-input hook keeps, numbered past the rollout's +training micro-batches, and hands the train-output hook what the forwards kept; nothing trains. + + rollout pairs ──train_input──► kept pairs ──► one no-grad forward per micro-batch, ids after the training ones + ──► reshard the models ──► train_output(ctx, kept pairs, the one list) +""" + +from tests.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=5, suite="stage-a-cpu", labels=["fsdp"]) + +import ast +from contextlib import nullcontext +from pathlib import Path +from typing import Any + +import torch +from tests.fast.backends.fsdp_utils.test_train_input_hook import _actor + +from miles.backends.fsdp_utils.loss_hub import LossHooks +from miles.utils.train_data_utils import build_microbatch_schedule + + +def _load_compute_core(resharded): + 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 == "_compute_core" + ) + namespace = dict( + Any=Any, + LossHooks=LossHooks, + torch=torch, + build_microbatch_schedule=build_microbatch_schedule, + timer=lambda name: nullcontext(), + new_metric_buffer=lambda *args, **kwargs: "metrics", + reshard_model=resharded.append, + ) + exec(compile(ast.Module(body=[method], type_ignores=[]), str(path), "exec"), namespace) + return namespace["_compute_core"] + + +def test_the_kept_pairs_forward_once_each_after_the_training_numbers(): + pairs = [{"sample_index": index} for index in range(6)] + forwarded, resharded, hooks_seen = [], [], [] + actor = _actor(None, None, forwarded) + actor.args.num_steps_per_rollout = 3 + actor.models = {"transformer": "critic"} + actor.reference_models = {"transformer": "reference"} + recorder = actor._forward_train_pair_batch + actor._forward_train_pair_batch = lambda ctx, chunk, **kwargs: ( + hooks_seen.append(kwargs["hooks"]), + recorder(ctx, chunk, **kwargs), + ) + hooks = LossHooks( + prepare=None, + formula=None, + train_input=lambda ctx, train_pairs: train_pairs[4:], + train_output=lambda ctx, train_pairs, inputs: (ctx.external_data, train_pairs, inputs), + ) + + output = _load_compute_core(resharded)( + actor, rollout_id=2, rollout_data={"train_data": pairs}, external_data={"scores": 1}, hooks=hooks + ) + + # Six training micro-batches (3 steps x 2) come first; the two kept pairs forward as 6 and 7, "at" the last step. + assert forwarded == [(6, 2, False, [pairs[4]]), (7, 2, False, [pairs[5]])] + assert hooks_seen == [hooks, hooks] + assert output == ({"scores": 1}, pairs[4:], [6, 7]) + assert resharded == ["critic", "reference"] + assert actor.global_step == 0 + + +def test_without_hooks_nothing_is_selected_or_returned(): + pairs = [{"sample_index": index} for index in range(2)] + forwarded, resharded = [], [] + actor = _actor(None, None, forwarded) + actor.args.num_steps_per_rollout = 1 + + output = _load_compute_core(resharded)( + actor, rollout_id=0, rollout_data={"train_data": pairs}, external_data={}, hooks=LossHooks(None, None) + ) + + assert forwarded == [(2, 0, False, [pairs[0]]), (3, 0, False, [pairs[1]])] + assert output is None diff --git a/tests/fast/backends/fsdp_utils/test_reference_models.py b/tests/fast/backends/fsdp_utils/test_reference_models.py index e90e271a2..f403c7bfd 100644 --- a/tests/fast/backends/fsdp_utils/test_reference_models.py +++ b/tests/fast/backends/fsdp_utils/test_reference_models.py @@ -139,6 +139,7 @@ def load_actor_forward_method(reshard_model=reshard_model): reshard_model=reshard_model, apply_input_dtype_policy=apply_input_dtype_policy, DiffusionLossContext=object, + LossHooks=object, MetricBuffer=object, ) exec(compile(ast.Module(body=[method], type_ignores=[]), str(path), "exec"), namespace) @@ -531,6 +532,36 @@ 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 test_the_trunk_runs_the_hooks_it_is_handed_instead_of_the_groups(): + model = torch.nn.Linear(3, 3) + harness, observed = make_actor_forward_harness({"block": model}, {}, "block", torch.ones(2, 3), "none") + seen = {} + + def prepare(ctx, batch, **kwargs): + seen["prepare"] = kwargs + return harness.loss_hooks.prepare(ctx, batch, **kwargs) + + def formula(ctx, batch, prepared, *, new_pred, **kwargs): + seen["formula"] = new_pred["visual"] + return None + + result = load_actor_forward_method()( + harness, + None, + [], + microbatch_id=5, + optim_step_idx=1, + train_output_inputs=[], + metrics=None, + hooks=SimpleNamespace(prepare=prepare, formula=formula), + ) + + assert result is None + assert seen["prepare"] == {"microbatch_id": 5, "optim_step_idx": 1, "pad_to_len": None} + torch.testing.assert_close(seen["formula"], model(torch.ones(2, 3))) + assert "new_pred" not in observed # the group's formula did not run + + def _teacher_harness(teacher_guidance_scale, *, with_teacher=True, true_cfg_scale=None): actor, teacher = TinyComponent(), TinyComponent() order = [] diff --git a/tests/fast/backends/fsdp_utils/test_train_output_handoff.py b/tests/fast/backends/fsdp_utils/test_train_output_handoff.py index 765ffdd85..fb763d31f 100644 --- a/tests/fast/backends/fsdp_utils/test_train_output_handoff.py +++ b/tests/fast/backends/fsdp_utils/test_train_output_handoff.py @@ -1,4 +1,4 @@ -"""FSDPTrainRayActor.train hands its output to later groups through the object store, not through the driver.""" +"""FSDPTrainRayActor.train and .compute hand their output to later groups through the object store, not the driver.""" from tests.ci.ci_register import register_cpu_ci @@ -39,6 +39,7 @@ def put(value): timer=lambda name: nullcontext(), inverse_timer=lambda name: nullcontext(), train_metric_utils=SimpleNamespace(log_perf_data_raw=lambda **kwargs: None), + get_loss_hooks=lambda args, hooks_key: ("hooks of", args.loss_type, hooks_key), ) exec(compile(ast.Module(body=methods, type_ignores=[]), str(path), "exec"), namespace) return namespace, store, put @@ -68,3 +69,31 @@ def train_core(rollout_id, rollout_data, external_data, optim_steps=None): assert isinstance(result, Box) assert store[result.inner] == {"scores": [3]} assert result.inner not in (shard.inner, critic_output.inner) + + +def test_compute_unboxes_external_data_and_boxes_its_output(): + namespace, store, put = _load_methods("compute") + seen = {} + + def compute_core(rollout_id, rollout_data, external_data, hooks): + seen.update(rollout_data=rollout_data, external_data=external_data, hooks=hooks) + return {"scores": [rollout_id]} + + actor = SimpleNamespace( + args=SimpleNamespace(offload_train=False, debug_rollout_only=False, loss_type="dmd2"), + _compute_core=compute_core, + parallel_state=SimpleNamespace(get_mesh=lambda name: SimpleNamespace(get_local_rank=lambda: 0)), + ) + shard = Box(put({"train_data": ["pair"]})) + critic_output = Box(put({"scores": [0]})) + + result = namespace["compute"](actor, 3, [shard], {"critic": critic_output}, "critic-scoring") + + assert seen == { + "rollout_data": {"train_data": ["pair"]}, + "external_data": {"critic": {"scores": [0]}}, + "hooks": ("hooks of", "dmd2", "critic-scoring"), + } + assert isinstance(result, Box) + assert store[result.inner] == {"scores": [3]} + assert result.inner not in (shard.inner, critic_output.inner) diff --git a/tests/fast/rollout/test_placement_group.py b/tests/fast/rollout/test_placement_group.py index 39650945e..8db8b7311 100644 --- a/tests/fast/rollout/test_placement_group.py +++ b/tests/fast/rollout/test_placement_group.py @@ -115,6 +115,7 @@ 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)) + self.compute = SimpleNamespace(remote=lambda *args: (rank, "compute", *args)) group = object.__new__(RayTrainGroup) group._actor_handlers = [_Handle(rank) for rank in range(2)] @@ -126,3 +127,7 @@ def __init__(self, rank): ] assert group.async_train(7, "data") == [(0, 7, "data", {}, None), (1, 7, "data", {}, None)] assert group.async_train(7, "data", optim_steps=(1, 3)) == [(0, 7, "data", {}, (1, 3)), (1, 7, "data", {}, (1, 3))] + assert group.async_compute(7, "data", external_data, "critic-scoring") == [ + (0, "compute", 7, "data", {"critic": "critic_0", "reward": "reward_0"}, "critic-scoring"), + (1, "compute", 7, "data", {"critic": "critic_1", "reward": "reward_1"}, "critic-scoring"), + ] From ac465bf184ace2b2264411d7727bcc533fd5d3e1 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Wed, 11 Nov 2026 10:38:13 +0000 Subject: [PATCH 4/7] feat(dmd2): add --dmd2-critic-scoring original, the reference's separate scoring forward `reuse-critic-step` (default, no behavior change): the critic's last training step draws in the scoring range, asks for the teacher and keeps both x0 as the score. `original`: that step is plain SFT and keeps nothing; the new `("dmd2", "critic-scoring")` hooks, run forward-only by `FSDPTrainRayActor.compute`, score the last step's pairs (`last_step_pairs`) at the scoring draw with the critic before its last update, as tianweiy/DMD2 does. Both modes share `prepare_scoring_batch` and `keep_scores`, so they score the same function of the same draw. Co-Authored-By: Claude Mythos 5.1 --- docs/user-guide/cli-reference.md | 1 + .../backends/fsdp_utils/loss_hub/__init__.py | 10 +- miles/backends/fsdp_utils/loss_hub/dmd2.py | 91 ++++++++++++++--- miles/utils/arguments.py | 11 +++ .../backends/fsdp_utils/test_loss_hub_dmd2.py | 98 +++++++++++++++++++ .../fsdp_utils/test_loss_hub_selection.py | 8 ++ 6 files changed, 205 insertions(+), 14 deletions(-) diff --git a/docs/user-guide/cli-reference.md b/docs/user-guide/cli-reference.md index c0635f9ef..320784ec5 100644 --- a/docs/user-guide/cli-reference.md +++ b/docs/user-guide/cli-reference.md @@ -289,6 +289,7 @@ See [Dtype Control](../advanced/dtype-control.md). | `--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 σ². | +| `--dmd2-critic-scoring` | str | `reuse-critic-step` | How the critic scores its last step's samples. `reuse-critic-step`: that step's training forward, drawn in `--dmd2-score-sigma-range`, is the score. `original`: the reference's separate draw and critic forward before the critic trains on them (one more critic forward per scored sample; under `--offload-train`, one more sleep/wake of each group). | | `--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. | diff --git a/miles/backends/fsdp_utils/loss_hub/__init__.py b/miles/backends/fsdp_utils/loss_hub/__init__.py index 651570b37..97f60bed5 100644 --- a/miles/backends/fsdp_utils/loss_hub/__init__.py +++ b/miles/backends/fsdp_utils/loss_hub/__init__.py @@ -12,9 +12,12 @@ from miles.backends.fsdp_utils.loss_hub.dmd2 import ( critic_loss_formula, dmd2_loss_formula, + last_step_pairs, prepare_critic_batch, prepare_generator_batch, + prepare_scoring_batch, score_last_step_samples, + scoring_formula, select_scored_pairs, ) from miles.backends.fsdp_utils.loss_hub.flow_grpo import flow_grpo_loss_formula, prepare_flow_grpo_batch @@ -50,11 +53,16 @@ class LossHooks: ("sft_loss", "actor"): LossHooks(prepare_sft_batch, sft_loss_formula), ("dmd2", "actor"): LossHooks(prepare_generator_batch, dmd2_loss_formula, train_input=select_scored_pairs), ("dmd2", "critic"): LossHooks(prepare_critic_batch, critic_loss_formula, train_output=score_last_step_samples), + # Forward-only, through FSDPTrainRayActor.compute: the critic's scoring under --dmd2-critic-scoring original. + ("dmd2", "critic-scoring"): LossHooks( + prepare_scoring_batch, scoring_formula, train_input=last_step_pairs, 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. + """The hooks of ``--loss-type`` for the trainer ``role``, or for a forward-only pass such as ``critic-scoring``; + only ``custom_loss`` reads the ``--custom-*-path`` flags. Under ``custom_loss`` an unset prepare or formula path falls back to Flow-GRPO's. """ diff --git a/miles/backends/fsdp_utils/loss_hub/dmd2.py b/miles/backends/fsdp_utils/loss_hub/dmd2.py index 371679c19..0ec41e00e 100644 --- a/miles/backends/fsdp_utils/loss_hub/dmd2.py +++ b/miles/backends/fsdp_utils/loss_hub/dmd2.py @@ -1,4 +1,10 @@ -"""DMD2 hooks: the critic group learns and scores the student's samples; the actor follows the scores.""" +"""DMD2 hooks: the critic group learns and scores the student's samples; the actor follows the scores. + +--dmd2-critic-scoring picks how the critic scores its last step's samples: ``reuse-critic-step`` scores them with +that step's training forward (the critic hooks' last step is the scoring batch), ``original`` scores them with a +separate forward-only pass (the ``critic-scoring`` hooks, run by ``FSDPTrainRayActor.compute``) before the critic +trains that step on them, as tianweiy/DMD2 does. +""" from __future__ import annotations @@ -22,19 +28,37 @@ 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 and - the teacher runs on them too. + Under --dmd2-critic-scoring reuse-critic-step the last step's samples are scored at their noisy inputs, so that + step prepares the scoring batch: grid points from the scoring range, the teacher asked for. """ - scoring = _is_scoring_step(ctx, optim_step_idx) + if _is_scoring_step(ctx, optim_step_idx): + return prepare_scoring_batch( + ctx, batch, microbatch_id=microbatch_id, optim_step_idx=optim_step_idx, pad_to_len=pad_to_len + ) + return prepare_sft_batch( + ctx, _sft_batch(ctx, batch), microbatch_id=microbatch_id, optim_step_idx=optim_step_idx, pad_to_len=pad_to_len + ) + + +def prepare_scoring_batch( + ctx: DiffusionLossContext, + batch: list[dict], + *, + microbatch_id: int, + optim_step_idx: int, + pad_to_len: int | None = None, +) -> PreparedBatch: + """The critic's SFT draw on the student's x0 at grid points in --dmd2-score-sigma-range, with the teacher asked + for at the same noisy inputs.""" 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, + grid_index_range=_score_grid_index_range(ctx), ) - return _request_teacher_forward(ctx, batch, prepared, pad_to_len=pad_to_len) if scoring else prepared + return _request_teacher_forward(ctx, batch, prepared, pad_to_len=pad_to_len) def _sft_batch(ctx: DiffusionLossContext, batch: list[dict]) -> list[dict]: @@ -98,14 +122,11 @@ def critic_loss_formula( 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() - 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)) + keep_scores(batch, prepared, new_pred, teacher_pred, train_output_inputs) if ctx.args.dmd2_critic_loss_space == "x0": + latents = prepared.latents["visual"] + sigmas = prepared.extras["sigmas"]["visual"].view(len(batch), *([1] * (latents.ndim - 1))) # 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}}) @@ -125,6 +146,44 @@ def critic_loss_formula( ) +def scoring_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, + teacher_pred: dict[str, torch.Tensor] | None = None, + metrics: MetricBuffer, + optim_step_idx: int, + train_output_inputs: list, + **kwargs, +) -> None: + """Keeps the critic's and the teacher's x0 at each noisy input and computes no loss. + + The forward-only scoring of --dmd2-critic-scoring original, before the critic trains its last step on these samples. + """ + keep_scores(batch, prepared, new_pred, teacher_pred, train_output_inputs) + return None + + +def keep_scores( + batch: list[dict], + prepared: PreparedBatch, + new_pred: dict[str, torch.Tensor], + teacher_pred: dict[str, torch.Tensor] | None, + train_output_inputs: list, +) -> None: + """Per sample, x0_fake = x_s - sigma v_critic and x0_real = x_s - sigma v_teacher, for score_last_step_samples.""" + latents = prepared.latents["visual"] + sigmas = prepared.extras["sigmas"]["visual"].view(len(batch), *([1] * (latents.ndim - 1))) + x0_fake = latents - sigmas * new_pred["visual"].detach().float() + 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)) + + def score_last_step_samples( ctx: DiffusionLossContext, train_pairs: list[dict], train_output_inputs: list ) -> dict[int, dict]: @@ -132,8 +191,14 @@ def score_last_step_samples( return {index: {"x0_real": real.cpu(), "x0_fake": fake.cpu()} for index, real, fake in train_output_inputs} +def last_step_pairs(ctx: DiffusionLossContext, train_pairs: list[dict]) -> list[dict]: + """The last 1/K of the rank's pairs, K the critic's steps per rollout: its last step's pairs, the ones it scores.""" + return train_pairs[len(train_pairs) - len(train_pairs) // ctx.args.num_steps_per_rollout :] + + def _is_scoring_step(ctx: DiffusionLossContext, optim_step_idx: int) -> bool: - return optim_step_idx == ctx.args.num_steps_per_rollout - 1 + """Under reuse-critic-step the last step's training forward is the critic's score; under original no step is.""" + return ctx.args.dmd2_critic_scoring == "reuse-critic-step" and optim_step_idx == ctx.args.num_steps_per_rollout - 1 def select_scored_pairs(ctx: DiffusionLossContext, train_pairs: list[dict]) -> list[dict]: diff --git a/miles/utils/arguments.py b/miles/utils/arguments.py index 2b26fdac3..2141c50fc 100644 --- a/miles/utils/arguments.py +++ b/miles/utils/arguments.py @@ -1056,6 +1056,17 @@ def add_algo_arguments(parser): 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( + "--dmd2-critic-scoring", + type=str, + choices=["reuse-critic-step", "original"], + default="reuse-critic-step", + help="How the DMD2 critic scores its last step's samples. reuse-critic-step: that step's training " + "forward, drawn in --dmd2-score-sigma-range, is the critic's score, so only the teacher's forward " + "is added. original: tianweiy/DMD2's order, a separate draw and critic forward on those samples " + "before the critic trains on them, which costs a critic forward per scored sample and, under " + "--offload-train, one more sleep/wake of each group.", + ) parser.add_argument( "--critic-load", type=str, 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 aa3a08501..d9bbcd4c3 100644 --- a/tests/fast/backends/fsdp_utils/test_loss_hub_dmd2.py +++ b/tests/fast/backends/fsdp_utils/test_loss_hub_dmd2.py @@ -46,6 +46,13 @@ 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 + +--dmd2-critic-scoring original: the critic's last step is plain SFT and scores nothing; the critic-scoring hooks +(run forward-only, before that step) score the last step's pairs at a fresh draw in the scoring range: + test_under_original_the_last_step_is_plain_sft full grid, no teacher, nothing kept + test_scoring_batch_is_the_last_step_batch_of_the_reuse the same prepare as the reuse mode's last step + test_scoring_formula_keeps_x0_and_no_loss returns None; the kept x0 == x_s - sigma v of each forward + test_last_step_pairs_are_the_ones_the_actor_trains_on last 1/K of the shard == select_scored_pairs' set """ from tests.ci.ci_register import register_cpu_ci @@ -132,6 +139,7 @@ def _ctx(teacher_guidance_scale=3.0, critic_scale=1.0): dmd2_teacher_guidance_scale=teacher_guidance_scale, dmd2_score_sigma_range=[0.02, 0.98], dmd2_critic_loss_space="velocity", + dmd2_critic_scoring="reuse-critic-step", ), forward_dtype=torch.float32, device=torch.device("cpu"), @@ -604,3 +612,93 @@ def test_health_metrics_are_recorded_overall_and_per_step(): 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) + + +def test_under_original_the_last_step_is_plain_sft(): + ctx = _ctx() + ctx.args.dmd2_critic_scoring = "original" + pairs = _pairs(256) + last_step = CRITIC_STEPS - 1 + + 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) + assert torch.equal(critic_batch.latents["visual"], sft_batch.latents["visual"]) + assert torch.equal(critic_batch.extras["target"]["visual"], sft_batch.extras["target"]["visual"]) + assert critic_batch.teacher_guidance_scale is None + assert critic_batch.neg_cond is None and critic_batch.joint_cond is None + inputs = [] + _critic_step(ctx, pairs[:4], last_step, inputs) + assert inputs == [] + + +@pytest.mark.parametrize("cfg_batching", [False, True]) +def test_scoring_batch_is_the_last_step_batch_of_the_reuse(cfg_batching): + pairs = _pairs(4) + ctx = _ctx(teacher_guidance_scale=3.0) + ctx.train_pipeline_config.cfg_batching = cfg_batching + reuse = dmd2.prepare_critic_batch(ctx, pairs, microbatch_id=9, optim_step_idx=CRITIC_STEPS - 1) + + ctx.args.dmd2_critic_scoring = "original" + # Whatever step the forward-only pass is numbered at: the draw is the scoring draw. + scoring = dmd2.prepare_scoring_batch(ctx, pairs, microbatch_id=9, optim_step_idx=0) + + for field in ("latents", "timesteps", "timesteps_for_model"): + assert torch.equal(getattr(scoring, field)["visual"], getattr(reuse, field)["visual"]) + assert torch.equal(scoring.extras["sigmas"]["visual"], reuse.extras["sigmas"]["visual"]) + assert scoring.teacher_guidance_scale == reuse.teacher_guidance_scale == 3.0 + for cond in ("pos_cond", "neg_cond", "joint_cond"): + reuse_cond, scoring_cond = getattr(reuse, cond), getattr(scoring, cond) + if reuse_cond is None: + assert scoring_cond is None + else: + assert torch.equal(scoring_cond["encoder_hidden_states"], reuse_cond["encoder_hidden_states"]) + + +def test_scoring_formula_keeps_x0_and_no_loss(): + ctx = _ctx(teacher_guidance_scale=1.0) + ctx.args.dmd2_critic_scoring = "original" + ctx.models["transformer"] = _NoisyInputVelocity() + config = ctx.train_pipeline_config + pairs = _pairs(3) + teacher = _CondVelocity(2.0) + + inputs = [] + prepared = dmd2.prepare_scoring_batch(ctx, pairs, microbatch_id=5, optim_step_idx=CRITIC_STEPS - 1) + with torch.no_grad(): + teacher_pred = _forward(config, teacher, prepared, use_cfg=False, cfg_batching=False, guidance_scale=1.0) + new_pred = _forward(config, prepared.model, prepared, use_cfg=False, cfg_batching=False, guidance_scale=1.0) + loss = dmd2.scoring_formula( + ctx, + pairs, + prepared, + new_pred=new_pred, + old_pred=None, + ref_pred=None, + teacher_pred=teacher_pred, + metrics=_Metrics(), + optim_step_idx=CRITIC_STEPS - 1, + train_output_inputs=inputs, + ) + scores = dmd2.score_last_step_samples(ctx, pairs, inputs) + + assert loss is None + assert list(scores) == [100, 101, 102] + x_s = prepared.latents["visual"] + sigma = prepared.extras["sigmas"]["visual"].view(-1, 1, 1, 1) + critic_velocity = x_s + prepared.timesteps_for_model["visual"].view(-1, 1, 1, 1) + for n, pair in enumerate(pairs): + assert torch.equal(scores[pair["sample_index"]]["x0_fake"], x_s[n] - sigma[n] * critic_velocity[n]) + torch.testing.assert_close(scores[pair["sample_index"]]["x0_real"], x_s[n] - sigma[n] * 2.0 * (1.0 + n)) + + +def test_last_step_pairs_are_the_ones_the_actor_trains_on(): + ctx = _ctx() + pairs = _pairs(9) + + kept = dmd2.last_step_pairs(ctx, pairs) + + assert kept == pairs[6:] + actor_ctx = _ctx() + actor_ctx.external_data["critic"] = {pair["sample_index"]: {} for pair in kept} + assert dmd2.select_scored_pairs(actor_ctx, pairs) == kept diff --git a/tests/fast/backends/fsdp_utils/test_loss_hub_selection.py b/tests/fast/backends/fsdp_utils/test_loss_hub_selection.py index 0f1019464..4723cc902 100644 --- a/tests/fast/backends/fsdp_utils/test_loss_hub_selection.py +++ b/tests/fast/backends/fsdp_utils/test_loss_hub_selection.py @@ -6,6 +6,8 @@ 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 + dmd2 / critic-scoring scoring prepare + scoring formula (no loss), train_input = last_step_pairs, + train_output = score_last_step_samples: the forward-only pass of the original scoring custom_loss / actor each --custom-*-path loaded; unset prepare / formula fall back to Flow-GRPO's no such (loss_type, role) ──► KeyError @@ -48,6 +50,12 @@ formula="miles.backends.fsdp_utils.loss_hub.dmd2.critic_loss_formula", train_output="miles.backends.fsdp_utils.loss_hub.dmd2.score_last_step_samples", ), + ("dmd2", "critic-scoring"): dict( + prepare="miles.backends.fsdp_utils.loss_hub.dmd2.prepare_scoring_batch", + formula="miles.backends.fsdp_utils.loss_hub.dmd2.scoring_formula", + train_input="miles.backends.fsdp_utils.loss_hub.dmd2.last_step_pairs", + train_output="miles.backends.fsdp_utils.loss_hub.dmd2.score_last_step_samples", + ), } From a48de7f7e09c8a41eec18769b6b4b5a0178b22a1 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Wed, 11 Nov 2026 10:41:00 +0000 Subject: [PATCH 5/7] feat(dmd2): train_dmd2.py, the driver that orders the critic and the actor within a rollout `--loss-type dmd2` runs through its own entrypoint, as async NFT does: under `reuse-critic-step` the critic trains and the actor trains on its scores; under `original` the critic trains steps 0..K-2, scores forward-only, the actor trains on the scores and the critic trains step K-1. A group saves after its last train of the rollout and, under --offload-train, sleeps before another group wakes. `train_diffusion.py` sends dmd2 here; the H3 recipe passes `train_script="train_dmd2.py"` (its reference evals keep train_diffusion.py). Co-Authored-By: Claude Mythos 5.1 --- docs/user-guide/customization.md | 5 + docs/user-guide/launch-script.md | 1 + ..._diffusion_dmd2_h3_t2va_16gpu_multinode.py | 2 + tests/fast/test_train_diffusion.py | 7 + tests/fast/test_train_dmd2.py | 191 ++++++++++++++++++ train_diffusion.py | 2 + train_dmd2.py | 135 +++++++++++++ 7 files changed, 343 insertions(+) create mode 100644 tests/fast/test_train_dmd2.py create mode 100644 train_dmd2.py diff --git a/docs/user-guide/customization.md b/docs/user-guide/customization.md index 09e7465f9..b2b4860ed 100644 --- a/docs/user-guide/customization.md +++ b/docs/user-guide/customization.md @@ -239,6 +239,7 @@ and optionally a train-input and a train-output hook: | `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` | +| `dmd2`, critic-scoring (forward only, `--dmd2-critic-scoring original`) | (the actor's pairs) | `loss_hub.dmd2.prepare_scoring_batch` | `scoring_formula` (no loss) | `last_step_pairs` / `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 @@ -252,6 +253,10 @@ On its last step its prepare hook also asks for the teacher at the same noisy in 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. +`dmd2` runs through `train_dmd2.py`, which orders the two groups within a rollout. Under +`--dmd2-critic-scoring original` the critic trains K−1 steps, then scores its last step's pairs +forward-only at a fresh draw (the `critic-scoring` hooks, through `FSDPTrainRayActor.compute`), the +actor trains on the scores, and the critic trains its last step. DiT forward always stays in the FSDP actor; the loss hook only computes the objective. diff --git a/docs/user-guide/launch-script.md b/docs/user-guide/launch-script.md index 77e015801..2acdfd14b 100644 --- a/docs/user-guide/launch-script.md +++ b/docs/user-guide/launch-script.md @@ -24,6 +24,7 @@ node's GPUs. | Command utilities | `miles/utils/external_utils/command_utils.py` | Starts Ray and submits the job | | Training entrypoint | `train_diffusion.py` | The train loop (~90 lines), run inside the Ray job | | SFT entrypoint | `train_sft.py` | The train-only loop with rollout prefetch; SFT recipes pass `train_script="train_sft.py"` | +| DMD2 entrypoint | `train_dmd2.py` | The critic / actor order within a rollout; the DMD2 recipe passes `train_script="train_dmd2.py"` | ## The structure of a launch script diff --git a/scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py b/scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py index b97892f75..8a923eef2 100644 --- a/scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py +++ b/scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py @@ -272,6 +272,8 @@ def execute(args: ScriptArgs, prompt_dir: str) -> None: f"{topology_args} {args.extra_args}" ), num_gpus_per_node=args.num_gpus_per_node, + # The reference evals run no DMD2 training. + train_script="train_diffusion.py" if args.reference else "train_dmd2.py", config=args, extra_env_vars={"PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True"}, ) diff --git a/tests/fast/test_train_diffusion.py b/tests/fast/test_train_diffusion.py index 8f5659811..3fe1ee410 100644 --- a/tests/fast/test_train_diffusion.py +++ b/tests/fast/test_train_diffusion.py @@ -84,6 +84,7 @@ def test_every_trainer_group_trains_each_rollout_in_order(monkeypatch, roles, of ) monkeypatch.setattr(train_diffusion.ray, "get", _fake_ray_get(events)) args = Namespace( + loss_type="policy_loss", start_rollout_id=0, num_rollout=2, offload_rollout=False, @@ -111,3 +112,9 @@ def test_every_trainer_group_trains_each_rollout_in_order(monkeypatch, roles, of expected += [("clear_memory", role) for role in roles] expected += [("update_weights", "actor")] assert events == expected + + +def test_dmd2_is_sent_to_its_own_driver(monkeypatch): + monkeypatch.setattr(train_diffusion, "configure_logger", lambda: None) + with pytest.raises(ValueError, match="run train_dmd2.py"): + train_diffusion.train(Namespace(loss_type="dmd2")) diff --git a/tests/fast/test_train_dmd2.py b/tests/fast/test_train_dmd2.py new file mode 100644 index 000000000..0cb527726 --- /dev/null +++ b/tests/fast/test_train_dmd2.py @@ -0,0 +1,191 @@ +"""train_dmd2.py orders the critic and the actor within a rollout as --dmd2-critic-scoring asks. + + reuse-critic-step critic trains (all K steps) ──► actor trains on its output + original critic trains steps 0..K-2 (none when K = 1) ──► critic scores, forward only + ──► actor trains on the scores ──► critic trains step K-1 + +The critic trains exactly K steps per rollout and the actor once; the scoring comes before the critic's last update. +A group saves after its last train of the rollout and, under --offload-train, sleeps before another group wakes. +""" + +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 + +import train_dmd2 + + +class _Ref: + def __init__(self, kind, role, rollout_id): + self.kind = kind + self.role = role + self.rollout_id = rollout_id + + +class _Remote: + def __init__(self, fn): + self.remote = fn + + +class _FakeRolloutManager: + def __init__(self): + self.generate = _Remote(lambda rollout_id: ("rollout_data", rollout_id)) + self.dispose = _Remote(lambda: None) + + +class _FakeTrainGroup: + def __init__(self, role, events): + self._role = role + self._events = events + + def async_train(self, rollout_id, rollout_data_ref, external_data=None, optim_steps=None): + received = { + role: [(ref.kind, ref.role, ref.rollout_id) for ref in refs] + for role, refs in (external_data or {}).items() + } + self._events.append(("train_start", self._role, rollout_id, rollout_data_ref, received, optim_steps)) + return [_Ref("train", self._role, rollout_id)] + + def async_compute(self, rollout_id, rollout_data_ref, external_data, hooks_key): + self._events.append(("compute_start", self._role, rollout_id, rollout_data_ref, external_data, hooks_key)) + return [_Ref("compute", self._role, rollout_id)] + + def save_model(self, rollout_id, force_sync=False): + self._events.append(("save_model", self._role, rollout_id, force_sync)) + + 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)) + + +def _fake_ray_get(events): + def get(ref): + if isinstance(ref, list): + return [get(r) for r in ref] + if isinstance(ref, _Ref): + events.append((f"{ref.kind}_done", ref.role, ref.rollout_id)) + return ref + + return get + + +def _run(monkeypatch, scoring, critic_steps, offload_train, num_rollout=2): + events = [] + monkeypatch.setattr(train_dmd2, "configure_logger", lambda: None) + monkeypatch.setattr(train_dmd2, "init_tracking", lambda args: None) + monkeypatch.setattr(train_dmd2, "create_placement_groups", lambda args: {"rollout": None}) + monkeypatch.setattr(train_dmd2, "create_rollout_manager", lambda args, pg: (_FakeRolloutManager(), None)) + monkeypatch.setattr( + train_dmd2, + "create_training_models", + lambda args, pgs, rollout_manager: {role: _FakeTrainGroup(role, events) for role in ("critic", "actor")}, + ) + monkeypatch.setattr(train_dmd2.ray, "get", _fake_ray_get(events)) + args = Namespace( + loss_type="dmd2", + dmd2_critic_scoring=scoring, + dmd2_critic_steps_per_rollout=critic_steps, + start_rollout_id=0, + num_rollout=num_rollout, + offload_rollout=False, + offload_train=offload_train, + eval_interval=None, + save_interval=1, + rollout_global_dataset=False, + ) + train_dmd2.train(args) + return events + + +def _rollout_events(scoring, critic_steps, offload_train, rollout_id, last): + data = ("rollout_data", rollout_id) + + def train(role, received, optim_steps): + return [("train_start", role, rollout_id, data, received, optim_steps), ("train_done", role, rollout_id)] + + def done(role): + return [("save_model", role, rollout_id, last)] + ([("offload", role)] if offload_train else []) + + if scoring == "reuse-critic-step": + expected = train("critic", {}, None) + done("critic") + expected += train("actor", {"critic": [("train", "critic", rollout_id)]}, None) + done("actor") + else: + expected = train("critic", {}, (0, critic_steps - 1)) if critic_steps > 1 else [] + expected += [ + ("compute_start", "critic", rollout_id, data, {}, "critic-scoring"), + ("compute_done", "critic", rollout_id), + ] + ([("offload", "critic")] if offload_train else []) + expected += train("actor", {"critic": [("compute", "critic", rollout_id)]}, None) + done("actor") + expected += train("critic", {}, (critic_steps - 1, critic_steps)) + done("critic") + if not offload_train: + expected += [("clear_memory", "critic"), ("clear_memory", "actor")] + return expected + [("update_weights", "actor")] + + +@pytest.mark.parametrize("offload_train", [False, True]) +@pytest.mark.parametrize(("scoring", "critic_steps"), [("reuse-critic-step", 3), ("original", 3), ("original", 1)]) +def test_each_rollout_runs_the_order_of_the_scoring_mode(monkeypatch, scoring, critic_steps, offload_train): + events = _run(monkeypatch, scoring, critic_steps, offload_train) + + expected = [("update_weights", "actor")] + for rollout_id in range(2): + expected += _rollout_events(scoring, critic_steps, offload_train, rollout_id, last=rollout_id == 1) + assert events == expected + + +def test_the_original_order_is_the_reference_s(): + """The explicit trace of one rollout with K = 3 under --offload-train.""" + expected = [ + ("train_start", "critic", 0, ("rollout_data", 0), {}, (0, 2)), + ("train_done", "critic", 0), + ("compute_start", "critic", 0, ("rollout_data", 0), {}, "critic-scoring"), + ("compute_done", "critic", 0), + ("offload", "critic"), + ("train_start", "actor", 0, ("rollout_data", 0), {"critic": [("compute", "critic", 0)]}, None), + ("train_done", "actor", 0), + ("save_model", "actor", 0, True), + ("offload", "actor"), + ("train_start", "critic", 0, ("rollout_data", 0), {}, (2, 3)), + ("train_done", "critic", 0), + ("save_model", "critic", 0, True), + ("offload", "critic"), + ("update_weights", "actor"), + ] + assert _rollout_events("original", 3, True, 0, last=True) == expected + + +@pytest.mark.parametrize("scoring", ["reuse-critic-step", "original"]) +@pytest.mark.parametrize("critic_steps", [1, 4]) +def test_the_critic_trains_k_steps_and_the_actor_once_after_the_scoring(monkeypatch, scoring, critic_steps): + events = [ + event + for event in _run(monkeypatch, scoring, critic_steps, False, num_rollout=1) + if event[0] != "update_weights" + ] + + critic_trains = [event for event in events if event[0] == "train_start" and event[1] == "critic"] + actor_trains = [event for event in events if event[0] == "train_start" and event[1] == "actor"] + steps_trained = sum(critic_steps if event[5] is None else event[5][1] - event[5][0] for event in critic_trains) + assert steps_trained == critic_steps + assert len(actor_trains) == 1 + # The actor's scores come from the critic before its last update. + actor_at = events.index(actor_trains[0]) + if scoring == "original": + assert events.index(("compute_done", "critic", 0)) < actor_at < events.index(critic_trains[-1]) + else: + assert events.index(("train_done", "critic", 0)) < actor_at + + +def test_other_loss_types_are_sent_to_train_diffusion(monkeypatch): + monkeypatch.setattr(train_dmd2, "configure_logger", lambda: None) + with pytest.raises(ValueError, match="run through train_diffusion.py"): + train_dmd2.train(Namespace(loss_type="nft")) diff --git a/train_diffusion.py b/train_diffusion.py index 9aea22dae..c18cab76a 100644 --- a/train_diffusion.py +++ b/train_diffusion.py @@ -12,6 +12,8 @@ def train(args): configure_logger() + if args.loss_type == "dmd2": + raise ValueError("--loss-type dmd2 orders its critic and actor within a rollout; run train_dmd2.py") logger = logging.getLogger(__name__) # allocate the GPUs logger.info("train: creating placement groups") diff --git a/train_dmd2.py b/train_dmd2.py new file mode 100644 index 000000000..cec1eaafb --- /dev/null +++ b/train_dmd2.py @@ -0,0 +1,135 @@ +"""DMD2: the critic group learns the student's samples and scores them; the actor follows the scores. + +Each rollout trains the two groups in the order --dmd2-critic-scoring asks for, K = --dmd2-critic-steps-per-rollout: + + reuse-critic-step critic trains its K steps, the last one scoring ──► actor trains on the scores + original critic trains steps 0..K-2 ──► critic scores, forward only ──► actor trains on the scores + ──► critic trains step K-1 + +A group saves after its last train of the rollout and, under --offload-train, sleeps before another group wakes. +""" + +import logging +import sys + +import ray + +from miles.ray.placement_group import create_placement_groups, create_rollout_manager, create_training_models +from miles.utils.arguments import parse_args +from miles.utils.logging_utils import configure_logger +from miles.utils.misc import should_run_periodic_action +from miles.utils.tracking_utils import init_tracking + +logger = logging.getLogger(__name__) + +SCORING_HOOKS = "critic-scoring" + + +def train_rollout(args, rollout_id, rollout_data_ref, train_groups, should_save): + """Train the critic and the actor on the rollout, in the order of --dmd2-critic-scoring.""" + critic, actor = train_groups["critic"], train_groups["actor"] + critic_steps = args.dmd2_critic_steps_per_rollout + + def train(group, role, external_data=None, optim_steps=None): + logger.info(f"train: rollout {rollout_id} {role} train start") + # Each rank returns a Box around its output's ObjectRef; the driver keeps the boxes (not the payload) + # and hands them to the later group, as RolloutManager.generate does for the shards. + output = ray.get(group.async_train(rollout_id, rollout_data_ref, external_data, optim_steps)) + logger.info(f"train: rollout {rollout_id} {role} train done") + return output + + def done(group): + """The group's last train of the rollout is over: save, and sleep before another group wakes.""" + if should_save: + group.save_model(rollout_id, force_sync=rollout_id == args.num_rollout - 1) + if args.offload_train: + group.offload() + + if args.dmd2_critic_scoring == "reuse-critic-step": + scores = train(critic, "critic") + done(critic) + train(actor, "actor", {"critic": scores}) + done(actor) + return + + if critic_steps > 1: + train(critic, "critic", optim_steps=(0, critic_steps - 1)) + logger.info(f"train: rollout {rollout_id} critic scoring start") + scores = ray.get(critic.async_compute(rollout_id, rollout_data_ref, {}, SCORING_HOOKS)) + logger.info(f"train: rollout {rollout_id} critic scoring done") + if args.offload_train: + critic.offload() + train(actor, "actor", {"critic": scores}) + done(actor) + train(critic, "critic", optim_steps=(critic_steps - 1, critic_steps)) + done(critic) + + +def train(args): + configure_logger() + if args.loss_type != "dmd2": + raise ValueError("train_dmd2.py runs --loss-type dmd2; the other loss types run through train_diffusion.py") + # allocate the GPUs + logger.info("train: creating placement groups") + pgs = create_placement_groups(args) + logger.info("train: placement groups ready") + init_tracking(args) + + # create the rollout manager, with sglang engines inside. + # need to initialize rollout manager first to calculate num_rollout + logger.info("train: creating rollout manager") + rollout_manager, num_rollout_per_epoch = create_rollout_manager(args, pgs["rollout"]) + logger.info("train: rollout manager ready") + + logger.info("train: creating training model") + train_groups = create_training_models(args, pgs, rollout_manager) + actor_model = train_groups["actor"] + logger.info("train: training model ready") + + if args.offload_rollout: + ray.get(rollout_manager.onload_weights.remote()) + + # always update weight first so that sglang has the loaded weights from training. + actor_model.update_weights() + + # special case for eval-only + if args.num_rollout == 0 and args.eval_interval is not None: + ray.get(rollout_manager.eval.remote(rollout_id=0)) + + for rollout_id in range(args.start_rollout_id, args.num_rollout): + logger.info(f"train: rollout {rollout_id} generate start") + if args.eval_interval is not None and rollout_id == 0 and not args.skip_eval_before_train: + ray.get(rollout_manager.eval.remote(rollout_id)) + + # generating rollout data + rollout_data_ref = ray.get(rollout_manager.generate.remote(rollout_id)) + logger.info(f"train: rollout {rollout_id} generate done") + + 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_rollout(args, rollout_id, rollout_data_ref, train_groups, should_save) + + 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() + + if should_run_periodic_action(rollout_id, args.eval_interval, num_rollout_per_epoch): + ray.get(rollout_manager.eval.remote(rollout_id)) + + ray.get(rollout_manager.dispose.remote()) + + +if __name__ == "__main__": + # Ensure stdout is line-buffered so nohup logs show progress immediately. + sys.stdout.reconfigure(line_buffering=True) + args = parse_args() + train(args) From 9fdaf3100839aeb8141ef0d5dc9f17f6dc3aa1d8 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Fri, 20 Nov 2026 21:40:11 +0000 Subject: [PATCH 6/7] refactor(dmd2): score the last step's samples inside the critic's train call under --dmd2-critic-scoring original The critic's last step does not depend on the actor's update, and the actor reads only the scores, so the scoring only has to precede that step's update, not the actor's train. A group's hooks can now declare a forward-only pass, `LossHooks.forward_only`: before the optimizer steps it names, the trunk runs its prepare and formula without grad on that step's micro-batches, numbered past the rollout's training ones. The DMD2 critic declares its scoring hooks there, so both modes run critic -> actor through train_diffusion.py, and train_dmd2.py goes. The critic's forwards and their order are the ones of the split calls: steps 0..K-2, the scoring forwards at micro-batch ids K*m.., step K-1. Suggested by Rockdu on #375. --- docs/user-guide/cli-reference.md | 2 +- docs/user-guide/customization.md | 8 +- docs/user-guide/launch-script.md | 1 - miles/backends/fsdp_utils/actor.py | 22 +- .../backends/fsdp_utils/loss_hub/__init__.py | 32 ++- miles/backends/fsdp_utils/loss_hub/dmd2.py | 14 +- miles/utils/arguments.py | 3 +- ..._diffusion_dmd2_h3_t2va_16gpu_multinode.py | 2 - .../backends/fsdp_utils/test_loss_hub_dmd2.py | 23 ++- .../fsdp_utils/test_loss_hub_selection.py | 24 ++- .../fsdp_utils/test_reference_models.py | 1 + .../fsdp_utils/test_train_input_hook.py | 41 +++- tests/fast/test_train_diffusion.py | 7 - tests/fast/test_train_dmd2.py | 191 ------------------ train_diffusion.py | 2 - train_dmd2.py | 135 ------------- 16 files changed, 120 insertions(+), 388 deletions(-) delete mode 100644 tests/fast/test_train_dmd2.py delete mode 100644 train_dmd2.py diff --git a/docs/user-guide/cli-reference.md b/docs/user-guide/cli-reference.md index 320784ec5..a9881a672 100644 --- a/docs/user-guide/cli-reference.md +++ b/docs/user-guide/cli-reference.md @@ -289,7 +289,7 @@ See [Dtype Control](../advanced/dtype-control.md). | `--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 σ². | -| `--dmd2-critic-scoring` | str | `reuse-critic-step` | How the critic scores its last step's samples. `reuse-critic-step`: that step's training forward, drawn in `--dmd2-score-sigma-range`, is the score. `original`: the reference's separate draw and critic forward before the critic trains on them (one more critic forward per scored sample; under `--offload-train`, one more sleep/wake of each group). | +| `--dmd2-critic-scoring` | str | `reuse-critic-step` | How the critic scores its last step's samples. `reuse-critic-step`: that step's training forward, drawn in `--dmd2-score-sigma-range`, is the score. `original`: the reference's separate draw and critic forward before the critic trains on them (one more critic forward per scored sample). | | `--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. | diff --git a/docs/user-guide/customization.md b/docs/user-guide/customization.md index b2b4860ed..c72dd19fe 100644 --- a/docs/user-guide/customization.md +++ b/docs/user-guide/customization.md @@ -239,7 +239,6 @@ and optionally a train-input and a train-output hook: | `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` | -| `dmd2`, critic-scoring (forward only, `--dmd2-critic-scoring original`) | (the actor's pairs) | `loss_hub.dmd2.prepare_scoring_batch` | `scoring_formula` (no loss) | `last_step_pairs` / `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 @@ -253,10 +252,9 @@ On its last step its prepare hook also asks for the teacher at the same noisy in 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. -`dmd2` runs through `train_dmd2.py`, which orders the two groups within a rollout. Under -`--dmd2-critic-scoring original` the critic trains K−1 steps, then scores its last step's pairs -forward-only at a fresh draw (the `critic-scoring` hooks, through `FSDPTrainRayActor.compute`), the -actor trains on the scores, and the critic trains its last step. +Under `--dmd2-critic-scoring original` the last step is plain SFT, and before it trains the trunk runs +the critic's `forward_only` hooks (`prepare_scoring_batch`, `scoring_formula`) without grad on that +step's pairs, at a fresh draw. DiT forward always stays in the FSDP actor; the loss hook only computes the objective. diff --git a/docs/user-guide/launch-script.md b/docs/user-guide/launch-script.md index 2acdfd14b..77e015801 100644 --- a/docs/user-guide/launch-script.md +++ b/docs/user-guide/launch-script.md @@ -24,7 +24,6 @@ node's GPUs. | Command utilities | `miles/utils/external_utils/command_utils.py` | Starts Ray and submits the job | | Training entrypoint | `train_diffusion.py` | The train loop (~90 lines), run inside the Ray job | | SFT entrypoint | `train_sft.py` | The train-only loop with rollout prefetch; SFT recipes pass `train_script="train_sft.py"` | -| DMD2 entrypoint | `train_dmd2.py` | The critic / actor order within a rollout; the DMD2 recipe passes `train_script="train_dmd2.py"` | ## The structure of a launch script diff --git a/miles/backends/fsdp_utils/actor.py b/miles/backends/fsdp_utils/actor.py index c7023de88..7720af8b9 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, LossHooks, get_loss_hooks +from .loss_hub import DiffusionLossContext, ForwardOnlyHooks, LossHooks, get_loss_hooks from .lr_scheduler import get_lr_scheduler from .metrics import new_metric_buffer from .mixed_precision import parse_dtype_from_str @@ -524,6 +524,8 @@ def _train_core( with timer("actor_train"): # The micro-batch ids of the full run, so a range draws the same noise as the whole rollout would. microbatch_id = sum(len(microbatch_ranges) for microbatch_ranges in microbatch_schedule[:step_lo]) + # past the training ids: no draw shared with a training forward + forward_only_microbatch_id = sum(len(microbatch_ranges) for microbatch_ranges in microbatch_schedule) for optim_step_idx in range(step_lo, step_hi): microbatch_ranges = microbatch_schedule[optim_step_idx] self.optimizer.zero_grad(set_to_none=True) @@ -543,6 +545,22 @@ def _train_core( num_rollout_steps=self.args.diffusion_num_steps, ) + forward_only = self.loss_hooks.forward_only + if forward_only is not None and forward_only.runs_before_step(loss_ctx, optim_step_idx): + with torch.no_grad(): + for pair_lo, pair_hi in microbatch_ranges: + self._forward_train_pair_batch( + loss_ctx, + train_pairs[pair_lo:pair_hi], + microbatch_id=forward_only_microbatch_id, + optim_step_idx=optim_step_idx, + train_output_inputs=train_output_inputs, + metrics=metrics, + pad_to_len=legacy_pad_to_len, + hooks=forward_only, + ) + forward_only_microbatch_id += 1 + for pair_lo, pair_hi in microbatch_ranges: chunk = train_pairs[pair_lo:pair_hi] loss_sum = self._forward_train_pair_batch( @@ -615,7 +633,7 @@ def _forward_train_pair_batch( pad_to_len: int | None = None, write_old_log_prob: bool = False, old_log_prob_from_new: bool = False, - hooks: LossHooks | None = None, + hooks: LossHooks | ForwardOnlyHooks | None = None, ) -> torch.Tensor | None: """Run one prepared diffusion micro-batch: number ``microbatch_id`` of the rollout, in optimizer step ``optim_step_idx``, through the group's hooks or ``hooks``.""" diff --git a/miles/backends/fsdp_utils/loss_hub/__init__.py b/miles/backends/fsdp_utils/loss_hub/__init__.py index 97f60bed5..2eb882cc6 100644 --- a/miles/backends/fsdp_utils/loss_hub/__init__.py +++ b/miles/backends/fsdp_utils/loss_hub/__init__.py @@ -12,7 +12,7 @@ from miles.backends.fsdp_utils.loss_hub.dmd2 import ( critic_loss_formula, dmd2_loss_formula, - last_step_pairs, + is_scored_before_training, prepare_critic_batch, prepare_generator_batch, prepare_scoring_batch, @@ -26,7 +26,20 @@ 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"] +__all__ = ["LOSS_HOOKS", "DiffusionLossContext", "ForwardOnlyHooks", "LossHooks", "PreparedBatch", "get_loss_hooks"] + + +@dataclass(frozen=True) +class ForwardOnlyHooks: + """A no-grad pass over an optimizer step's micro-batches, run before the step trains them. + + It runs before the steps ``runs_before_step(ctx, optim_step_idx)`` names. ``prepare`` and ``formula`` are called + as a ``LossHooks``' are, with micro-batch ids past the rollout's training ones; the formula returns no loss. + """ + + runs_before_step: Callable[[DiffusionLossContext, int], bool] + prepare: Callable[..., PreparedBatch] + formula: Callable[..., None] @dataclass(frozen=True) @@ -38,13 +51,14 @@ class LossHooks: ...)`` 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. + this train call, those of ``forward_only`` included. """ prepare: Callable[..., PreparedBatch] formula: Callable[..., torch.Tensor | None] train_input: Callable[[DiffusionLossContext, list], list] | None = None train_output: Callable[[DiffusionLossContext, list, list], Any] | None = None + forward_only: ForwardOnlyHooks | None = None LOSS_HOOKS: dict[tuple[str, str], LossHooks] = { @@ -52,17 +66,17 @@ class LossHooks: ("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), - # Forward-only, through FSDPTrainRayActor.compute: the critic's scoring under --dmd2-critic-scoring original. - ("dmd2", "critic-scoring"): LossHooks( - prepare_scoring_batch, scoring_formula, train_input=last_step_pairs, train_output=score_last_step_samples + ("dmd2", "critic"): LossHooks( + prepare_critic_batch, + critic_loss_formula, + train_output=score_last_step_samples, + forward_only=ForwardOnlyHooks(is_scored_before_training, prepare_scoring_batch, scoring_formula), ), } def get_loss_hooks(args: Namespace, role: str) -> LossHooks: - """The hooks of ``--loss-type`` for the trainer ``role``, or for a forward-only pass such as ``critic-scoring``; - only ``custom_loss`` reads the ``--custom-*-path`` flags. + """The hooks of ``--loss-type`` for the trainer ``role``; only ``custom_loss`` reads the ``--custom-*-path`` flags. Under ``custom_loss`` an unset prepare or formula path falls back to Flow-GRPO's. """ diff --git a/miles/backends/fsdp_utils/loss_hub/dmd2.py b/miles/backends/fsdp_utils/loss_hub/dmd2.py index 0ec41e00e..f5a031f9c 100644 --- a/miles/backends/fsdp_utils/loss_hub/dmd2.py +++ b/miles/backends/fsdp_utils/loss_hub/dmd2.py @@ -2,8 +2,8 @@ --dmd2-critic-scoring picks how the critic scores its last step's samples: ``reuse-critic-step`` scores them with that step's training forward (the critic hooks' last step is the scoring batch), ``original`` scores them with a -separate forward-only pass (the ``critic-scoring`` hooks, run by ``FSDPTrainRayActor.compute``) before the critic -trains that step on them, as tianweiy/DMD2 does. +separate forward-only pass (the critic's ``forward_only`` hooks) before the critic trains that step on them, as +tianweiy/DMD2 does. """ from __future__ import annotations @@ -191,16 +191,16 @@ def score_last_step_samples( return {index: {"x0_real": real.cpu(), "x0_fake": fake.cpu()} for index, real, fake in train_output_inputs} -def last_step_pairs(ctx: DiffusionLossContext, train_pairs: list[dict]) -> list[dict]: - """The last 1/K of the rank's pairs, K the critic's steps per rollout: its last step's pairs, the ones it scores.""" - return train_pairs[len(train_pairs) - len(train_pairs) // ctx.args.num_steps_per_rollout :] - - def _is_scoring_step(ctx: DiffusionLossContext, optim_step_idx: int) -> bool: """Under reuse-critic-step the last step's training forward is the critic's score; under original no step is.""" return ctx.args.dmd2_critic_scoring == "reuse-critic-step" and optim_step_idx == ctx.args.num_steps_per_rollout - 1 +def is_scored_before_training(ctx: DiffusionLossContext, optim_step_idx: int) -> bool: + """Under original the last step's samples are scored forward-only, before the critic trains that step.""" + return ctx.args.dmd2_critic_scoring == "original" and optim_step_idx == ctx.args.num_steps_per_rollout - 1 + + 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"] diff --git a/miles/utils/arguments.py b/miles/utils/arguments.py index 2141c50fc..035ee2112 100644 --- a/miles/utils/arguments.py +++ b/miles/utils/arguments.py @@ -1064,8 +1064,7 @@ def add_algo_arguments(parser): help="How the DMD2 critic scores its last step's samples. reuse-critic-step: that step's training " "forward, drawn in --dmd2-score-sigma-range, is the critic's score, so only the teacher's forward " "is added. original: tianweiy/DMD2's order, a separate draw and critic forward on those samples " - "before the critic trains on them, which costs a critic forward per scored sample and, under " - "--offload-train, one more sleep/wake of each group.", + "before the critic trains on them, which costs a critic forward per scored sample.", ) parser.add_argument( "--critic-load", diff --git a/scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py b/scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py index 8a923eef2..b97892f75 100644 --- a/scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py +++ b/scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py @@ -272,8 +272,6 @@ def execute(args: ScriptArgs, prompt_dir: str) -> None: f"{topology_args} {args.extra_args}" ), num_gpus_per_node=args.num_gpus_per_node, - # The reference evals run no DMD2 training. - train_script="train_diffusion.py" if args.reference else "train_dmd2.py", config=args, extra_env_vars={"PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True"}, ) 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 d9bbcd4c3..9a1bcb2f0 100644 --- a/tests/fast/backends/fsdp_utils/test_loss_hub_dmd2.py +++ b/tests/fast/backends/fsdp_utils/test_loss_hub_dmd2.py @@ -47,12 +47,12 @@ 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 ---dmd2-critic-scoring original: the critic's last step is plain SFT and scores nothing; the critic-scoring hooks -(run forward-only, before that step) score the last step's pairs at a fresh draw in the scoring range: +--dmd2-critic-scoring original: the critic's last step is plain SFT and scores nothing; the forward-only hooks +(run before that step) score the last step's pairs at a fresh draw in the scoring range: test_under_original_the_last_step_is_plain_sft full grid, no teacher, nothing kept test_scoring_batch_is_the_last_step_batch_of_the_reuse the same prepare as the reuse mode's last step test_scoring_formula_keeps_x0_and_no_loss returns None; the kept x0 == x_s - sigma v of each forward - test_last_step_pairs_are_the_ones_the_actor_trains_on last 1/K of the shard == select_scored_pairs' set + test_either_mode_scores_the_last_step_once by its training forward or before it, never both or neither """ from tests.ci.ci_register import register_cpu_ci @@ -692,13 +692,14 @@ def test_scoring_formula_keeps_x0_and_no_loss(): torch.testing.assert_close(scores[pair["sample_index"]]["x0_real"], x_s[n] - sigma[n] * 2.0 * (1.0 + n)) -def test_last_step_pairs_are_the_ones_the_actor_trains_on(): +@pytest.mark.parametrize("critic_scoring", ["reuse-critic-step", "original"]) +def test_either_mode_scores_the_last_step_once(critic_scoring): + """A step scored twice or not at all leaves the actor the wrong scores, or none, without an error.""" ctx = _ctx() - pairs = _pairs(9) - - kept = dmd2.last_step_pairs(ctx, pairs) + ctx.args.dmd2_critic_scoring = critic_scoring - assert kept == pairs[6:] - actor_ctx = _ctx() - actor_ctx.external_data["critic"] = {pair["sample_index"]: {} for pair in kept} - assert dmd2.select_scored_pairs(actor_ctx, pairs) == kept + for step in range(CRITIC_STEPS): + by_training_forward = dmd2._is_scoring_step(ctx, step) + before_training = dmd2.is_scored_before_training(ctx, step) + assert by_training_forward + before_training == (step == CRITIC_STEPS - 1) + assert dmd2.is_scored_before_training(ctx, CRITIC_STEPS - 1) == (critic_scoring == "original") 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 4723cc902..80149d944 100644 --- a/tests/fast/backends/fsdp_utils/test_loss_hub_selection.py +++ b/tests/fast/backends/fsdp_utils/test_loss_hub_selection.py @@ -1,13 +1,13 @@ """--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) + (loss_type, role) ──► LossHooks(prepare, formula, train_input, train_output, forward_only) 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 - dmd2 / critic-scoring scoring prepare + scoring formula (no loss), train_input = last_step_pairs, - train_output = score_last_step_samples: the forward-only pass of the original scoring + dmd2 / critic critic prepare + critic formula, train_output = score_last_step_samples, + forward_only = scoring prepare + scoring formula (no loss) before the steps + is_scored_before_training names custom_loss / actor each --custom-*-path loaded; unset prepare / formula fall back to Flow-GRPO's no such (loss_type, role) ──► KeyError @@ -23,7 +23,7 @@ import pytest -from miles.backends.fsdp_utils.loss_hub import LOSS_HOOKS, LossHooks, get_loss_hooks +from miles.backends.fsdp_utils.loss_hub import LOSS_HOOKS, ForwardOnlyHooks, 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 @@ -49,12 +49,11 @@ 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", - ), - ("dmd2", "critic-scoring"): dict( - prepare="miles.backends.fsdp_utils.loss_hub.dmd2.prepare_scoring_batch", - formula="miles.backends.fsdp_utils.loss_hub.dmd2.scoring_formula", - train_input="miles.backends.fsdp_utils.loss_hub.dmd2.last_step_pairs", - train_output="miles.backends.fsdp_utils.loss_hub.dmd2.score_last_step_samples", + forward_only=dict( + runs_before_step="miles.backends.fsdp_utils.loss_hub.dmd2.is_scored_before_training", + prepare="miles.backends.fsdp_utils.loss_hub.dmd2.prepare_scoring_batch", + formula="miles.backends.fsdp_utils.loss_hub.dmd2.scoring_formula", + ), ), } @@ -75,11 +74,14 @@ def test_builtin_hooks_are_the_functions_the_paths_named(loss_type, role): assert hooks is LOSS_HOOKS[(loss_type, role)] paths = HOOK_PATHS_BY_LOSS_TYPE_AND_ROLE[(loss_type, role)] + forward_only_paths = paths.get("forward_only") 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")), + forward_only=forward_only_paths + and ForwardOnlyHooks(**{name: load_function(path) for name, path in forward_only_paths.items()}), ) diff --git a/tests/fast/backends/fsdp_utils/test_reference_models.py b/tests/fast/backends/fsdp_utils/test_reference_models.py index f403c7bfd..863c3c586 100644 --- a/tests/fast/backends/fsdp_utils/test_reference_models.py +++ b/tests/fast/backends/fsdp_utils/test_reference_models.py @@ -139,6 +139,7 @@ def load_actor_forward_method(reshard_model=reshard_model): reshard_model=reshard_model, apply_input_dtype_policy=apply_input_dtype_policy, DiffusionLossContext=object, + ForwardOnlyHooks=object, LossHooks=object, MetricBuffer=object, ) 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 25698ff0a..3581dc40d 100644 --- a/tests/fast/backends/fsdp_utils/test_train_input_hook.py +++ b/tests/fast/backends/fsdp_utils/test_train_input_hook.py @@ -7,7 +7,8 @@ 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. +window; the old-log-prob recompute of windows 1.. reuses their training forwards' numbers. A group's forward-only hooks +run without grad on a step's micro-batches before that step trains, numbered past the rollout's training ones. The production _train_core runs on CPU with the forward, metrics and rank checks replaced; the optimizer step is skipped, so only the pairs, ctx and numbers each stage receives are observed. @@ -72,7 +73,7 @@ def _actor(train_input, train_output, forwarded, **args): ), _forward_dtype=torch.float32, parallel_state=SimpleNamespace(dp_rank=0, dp_group=None), - loss_hooks=SimpleNamespace(train_input=train_input, train_output=train_output), + loss_hooks=SimpleNamespace(train_input=train_input, train_output=train_output, forward_only=None), optimizer=SimpleNamespace(zero_grad=lambda set_to_none: None), global_step=0, _maybe_legacy_window_pad_len=lambda train_pairs, microbatch_ranges: None, @@ -156,3 +157,39 @@ def test_the_recompute_passes_the_numbers_of_the_training_forwards_of_windows_1_ 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 + + +def test_the_forward_only_pass_runs_before_its_steps_train_numbered_past_the_training_micro_batches(): + pairs = [{"sample_index": index} for index in range(6)] + forwarded, hooks_and_grad_modes = [], [] + actor = _actor(None, lambda ctx, train_pairs, inputs: inputs, forwarded) + actor.args.num_steps_per_rollout = 3 + forward_only = SimpleNamespace(runs_before_step=lambda ctx, optim_step_idx: optim_step_idx >= 1) + actor.loss_hooks.forward_only = forward_only + record_forward = actor._forward_train_pair_batch + + def forward(ctx, chunk, **kwargs): + hooks_and_grad_modes.append((kwargs.get("hooks"), torch.is_grad_enabled())) + record_forward(ctx, chunk, **kwargs) + + actor._forward_train_pair_batch = forward + + train_output_inputs = _load_train_core()(actor, rollout_id=0, rollout_data={"train_data": pairs}, external_data={}) + + # 3 steps x 2 micro-batches train as 0..5; the passes before steps 1 and 2 count on from 6. + assert forwarded == [ + (0, 0, False, [pairs[0]]), + (1, 0, False, [pairs[1]]), + (6, 1, False, [pairs[2]]), + (7, 1, False, [pairs[3]]), + (2, 1, False, [pairs[2]]), + (3, 1, False, [pairs[3]]), + (8, 2, False, [pairs[4]]), + (9, 2, False, [pairs[5]]), + (4, 2, False, [pairs[4]]), + (5, 2, False, [pairs[5]]), + ] + training, forward_only_pass = [(None, True)] * 2, [(forward_only, False)] * 2 + assert hooks_and_grad_modes == training + (forward_only_pass + training) * 2 + # The train-output hook receives what both kinds of forward kept, in the order they ran. + assert train_output_inputs == [0, 1, 6, 7, 2, 3, 8, 9, 4, 5] diff --git a/tests/fast/test_train_diffusion.py b/tests/fast/test_train_diffusion.py index 3fe1ee410..8f5659811 100644 --- a/tests/fast/test_train_diffusion.py +++ b/tests/fast/test_train_diffusion.py @@ -84,7 +84,6 @@ def test_every_trainer_group_trains_each_rollout_in_order(monkeypatch, roles, of ) monkeypatch.setattr(train_diffusion.ray, "get", _fake_ray_get(events)) args = Namespace( - loss_type="policy_loss", start_rollout_id=0, num_rollout=2, offload_rollout=False, @@ -112,9 +111,3 @@ def test_every_trainer_group_trains_each_rollout_in_order(monkeypatch, roles, of expected += [("clear_memory", role) for role in roles] expected += [("update_weights", "actor")] assert events == expected - - -def test_dmd2_is_sent_to_its_own_driver(monkeypatch): - monkeypatch.setattr(train_diffusion, "configure_logger", lambda: None) - with pytest.raises(ValueError, match="run train_dmd2.py"): - train_diffusion.train(Namespace(loss_type="dmd2")) diff --git a/tests/fast/test_train_dmd2.py b/tests/fast/test_train_dmd2.py deleted file mode 100644 index 0cb527726..000000000 --- a/tests/fast/test_train_dmd2.py +++ /dev/null @@ -1,191 +0,0 @@ -"""train_dmd2.py orders the critic and the actor within a rollout as --dmd2-critic-scoring asks. - - reuse-critic-step critic trains (all K steps) ──► actor trains on its output - original critic trains steps 0..K-2 (none when K = 1) ──► critic scores, forward only - ──► actor trains on the scores ──► critic trains step K-1 - -The critic trains exactly K steps per rollout and the actor once; the scoring comes before the critic's last update. -A group saves after its last train of the rollout and, under --offload-train, sleeps before another group wakes. -""" - -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 - -import train_dmd2 - - -class _Ref: - def __init__(self, kind, role, rollout_id): - self.kind = kind - self.role = role - self.rollout_id = rollout_id - - -class _Remote: - def __init__(self, fn): - self.remote = fn - - -class _FakeRolloutManager: - def __init__(self): - self.generate = _Remote(lambda rollout_id: ("rollout_data", rollout_id)) - self.dispose = _Remote(lambda: None) - - -class _FakeTrainGroup: - def __init__(self, role, events): - self._role = role - self._events = events - - def async_train(self, rollout_id, rollout_data_ref, external_data=None, optim_steps=None): - received = { - role: [(ref.kind, ref.role, ref.rollout_id) for ref in refs] - for role, refs in (external_data or {}).items() - } - self._events.append(("train_start", self._role, rollout_id, rollout_data_ref, received, optim_steps)) - return [_Ref("train", self._role, rollout_id)] - - def async_compute(self, rollout_id, rollout_data_ref, external_data, hooks_key): - self._events.append(("compute_start", self._role, rollout_id, rollout_data_ref, external_data, hooks_key)) - return [_Ref("compute", self._role, rollout_id)] - - def save_model(self, rollout_id, force_sync=False): - self._events.append(("save_model", self._role, rollout_id, force_sync)) - - 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)) - - -def _fake_ray_get(events): - def get(ref): - if isinstance(ref, list): - return [get(r) for r in ref] - if isinstance(ref, _Ref): - events.append((f"{ref.kind}_done", ref.role, ref.rollout_id)) - return ref - - return get - - -def _run(monkeypatch, scoring, critic_steps, offload_train, num_rollout=2): - events = [] - monkeypatch.setattr(train_dmd2, "configure_logger", lambda: None) - monkeypatch.setattr(train_dmd2, "init_tracking", lambda args: None) - monkeypatch.setattr(train_dmd2, "create_placement_groups", lambda args: {"rollout": None}) - monkeypatch.setattr(train_dmd2, "create_rollout_manager", lambda args, pg: (_FakeRolloutManager(), None)) - monkeypatch.setattr( - train_dmd2, - "create_training_models", - lambda args, pgs, rollout_manager: {role: _FakeTrainGroup(role, events) for role in ("critic", "actor")}, - ) - monkeypatch.setattr(train_dmd2.ray, "get", _fake_ray_get(events)) - args = Namespace( - loss_type="dmd2", - dmd2_critic_scoring=scoring, - dmd2_critic_steps_per_rollout=critic_steps, - start_rollout_id=0, - num_rollout=num_rollout, - offload_rollout=False, - offload_train=offload_train, - eval_interval=None, - save_interval=1, - rollout_global_dataset=False, - ) - train_dmd2.train(args) - return events - - -def _rollout_events(scoring, critic_steps, offload_train, rollout_id, last): - data = ("rollout_data", rollout_id) - - def train(role, received, optim_steps): - return [("train_start", role, rollout_id, data, received, optim_steps), ("train_done", role, rollout_id)] - - def done(role): - return [("save_model", role, rollout_id, last)] + ([("offload", role)] if offload_train else []) - - if scoring == "reuse-critic-step": - expected = train("critic", {}, None) + done("critic") - expected += train("actor", {"critic": [("train", "critic", rollout_id)]}, None) + done("actor") - else: - expected = train("critic", {}, (0, critic_steps - 1)) if critic_steps > 1 else [] - expected += [ - ("compute_start", "critic", rollout_id, data, {}, "critic-scoring"), - ("compute_done", "critic", rollout_id), - ] + ([("offload", "critic")] if offload_train else []) - expected += train("actor", {"critic": [("compute", "critic", rollout_id)]}, None) + done("actor") - expected += train("critic", {}, (critic_steps - 1, critic_steps)) + done("critic") - if not offload_train: - expected += [("clear_memory", "critic"), ("clear_memory", "actor")] - return expected + [("update_weights", "actor")] - - -@pytest.mark.parametrize("offload_train", [False, True]) -@pytest.mark.parametrize(("scoring", "critic_steps"), [("reuse-critic-step", 3), ("original", 3), ("original", 1)]) -def test_each_rollout_runs_the_order_of_the_scoring_mode(monkeypatch, scoring, critic_steps, offload_train): - events = _run(monkeypatch, scoring, critic_steps, offload_train) - - expected = [("update_weights", "actor")] - for rollout_id in range(2): - expected += _rollout_events(scoring, critic_steps, offload_train, rollout_id, last=rollout_id == 1) - assert events == expected - - -def test_the_original_order_is_the_reference_s(): - """The explicit trace of one rollout with K = 3 under --offload-train.""" - expected = [ - ("train_start", "critic", 0, ("rollout_data", 0), {}, (0, 2)), - ("train_done", "critic", 0), - ("compute_start", "critic", 0, ("rollout_data", 0), {}, "critic-scoring"), - ("compute_done", "critic", 0), - ("offload", "critic"), - ("train_start", "actor", 0, ("rollout_data", 0), {"critic": [("compute", "critic", 0)]}, None), - ("train_done", "actor", 0), - ("save_model", "actor", 0, True), - ("offload", "actor"), - ("train_start", "critic", 0, ("rollout_data", 0), {}, (2, 3)), - ("train_done", "critic", 0), - ("save_model", "critic", 0, True), - ("offload", "critic"), - ("update_weights", "actor"), - ] - assert _rollout_events("original", 3, True, 0, last=True) == expected - - -@pytest.mark.parametrize("scoring", ["reuse-critic-step", "original"]) -@pytest.mark.parametrize("critic_steps", [1, 4]) -def test_the_critic_trains_k_steps_and_the_actor_once_after_the_scoring(monkeypatch, scoring, critic_steps): - events = [ - event - for event in _run(monkeypatch, scoring, critic_steps, False, num_rollout=1) - if event[0] != "update_weights" - ] - - critic_trains = [event for event in events if event[0] == "train_start" and event[1] == "critic"] - actor_trains = [event for event in events if event[0] == "train_start" and event[1] == "actor"] - steps_trained = sum(critic_steps if event[5] is None else event[5][1] - event[5][0] for event in critic_trains) - assert steps_trained == critic_steps - assert len(actor_trains) == 1 - # The actor's scores come from the critic before its last update. - actor_at = events.index(actor_trains[0]) - if scoring == "original": - assert events.index(("compute_done", "critic", 0)) < actor_at < events.index(critic_trains[-1]) - else: - assert events.index(("train_done", "critic", 0)) < actor_at - - -def test_other_loss_types_are_sent_to_train_diffusion(monkeypatch): - monkeypatch.setattr(train_dmd2, "configure_logger", lambda: None) - with pytest.raises(ValueError, match="run through train_diffusion.py"): - train_dmd2.train(Namespace(loss_type="nft")) diff --git a/train_diffusion.py b/train_diffusion.py index c18cab76a..9aea22dae 100644 --- a/train_diffusion.py +++ b/train_diffusion.py @@ -12,8 +12,6 @@ def train(args): configure_logger() - if args.loss_type == "dmd2": - raise ValueError("--loss-type dmd2 orders its critic and actor within a rollout; run train_dmd2.py") logger = logging.getLogger(__name__) # allocate the GPUs logger.info("train: creating placement groups") diff --git a/train_dmd2.py b/train_dmd2.py deleted file mode 100644 index cec1eaafb..000000000 --- a/train_dmd2.py +++ /dev/null @@ -1,135 +0,0 @@ -"""DMD2: the critic group learns the student's samples and scores them; the actor follows the scores. - -Each rollout trains the two groups in the order --dmd2-critic-scoring asks for, K = --dmd2-critic-steps-per-rollout: - - reuse-critic-step critic trains its K steps, the last one scoring ──► actor trains on the scores - original critic trains steps 0..K-2 ──► critic scores, forward only ──► actor trains on the scores - ──► critic trains step K-1 - -A group saves after its last train of the rollout and, under --offload-train, sleeps before another group wakes. -""" - -import logging -import sys - -import ray - -from miles.ray.placement_group import create_placement_groups, create_rollout_manager, create_training_models -from miles.utils.arguments import parse_args -from miles.utils.logging_utils import configure_logger -from miles.utils.misc import should_run_periodic_action -from miles.utils.tracking_utils import init_tracking - -logger = logging.getLogger(__name__) - -SCORING_HOOKS = "critic-scoring" - - -def train_rollout(args, rollout_id, rollout_data_ref, train_groups, should_save): - """Train the critic and the actor on the rollout, in the order of --dmd2-critic-scoring.""" - critic, actor = train_groups["critic"], train_groups["actor"] - critic_steps = args.dmd2_critic_steps_per_rollout - - def train(group, role, external_data=None, optim_steps=None): - logger.info(f"train: rollout {rollout_id} {role} train start") - # Each rank returns a Box around its output's ObjectRef; the driver keeps the boxes (not the payload) - # and hands them to the later group, as RolloutManager.generate does for the shards. - output = ray.get(group.async_train(rollout_id, rollout_data_ref, external_data, optim_steps)) - logger.info(f"train: rollout {rollout_id} {role} train done") - return output - - def done(group): - """The group's last train of the rollout is over: save, and sleep before another group wakes.""" - if should_save: - group.save_model(rollout_id, force_sync=rollout_id == args.num_rollout - 1) - if args.offload_train: - group.offload() - - if args.dmd2_critic_scoring == "reuse-critic-step": - scores = train(critic, "critic") - done(critic) - train(actor, "actor", {"critic": scores}) - done(actor) - return - - if critic_steps > 1: - train(critic, "critic", optim_steps=(0, critic_steps - 1)) - logger.info(f"train: rollout {rollout_id} critic scoring start") - scores = ray.get(critic.async_compute(rollout_id, rollout_data_ref, {}, SCORING_HOOKS)) - logger.info(f"train: rollout {rollout_id} critic scoring done") - if args.offload_train: - critic.offload() - train(actor, "actor", {"critic": scores}) - done(actor) - train(critic, "critic", optim_steps=(critic_steps - 1, critic_steps)) - done(critic) - - -def train(args): - configure_logger() - if args.loss_type != "dmd2": - raise ValueError("train_dmd2.py runs --loss-type dmd2; the other loss types run through train_diffusion.py") - # allocate the GPUs - logger.info("train: creating placement groups") - pgs = create_placement_groups(args) - logger.info("train: placement groups ready") - init_tracking(args) - - # create the rollout manager, with sglang engines inside. - # need to initialize rollout manager first to calculate num_rollout - logger.info("train: creating rollout manager") - rollout_manager, num_rollout_per_epoch = create_rollout_manager(args, pgs["rollout"]) - logger.info("train: rollout manager ready") - - logger.info("train: creating training model") - train_groups = create_training_models(args, pgs, rollout_manager) - actor_model = train_groups["actor"] - logger.info("train: training model ready") - - if args.offload_rollout: - ray.get(rollout_manager.onload_weights.remote()) - - # always update weight first so that sglang has the loaded weights from training. - actor_model.update_weights() - - # special case for eval-only - if args.num_rollout == 0 and args.eval_interval is not None: - ray.get(rollout_manager.eval.remote(rollout_id=0)) - - for rollout_id in range(args.start_rollout_id, args.num_rollout): - logger.info(f"train: rollout {rollout_id} generate start") - if args.eval_interval is not None and rollout_id == 0 and not args.skip_eval_before_train: - ray.get(rollout_manager.eval.remote(rollout_id)) - - # generating rollout data - rollout_data_ref = ray.get(rollout_manager.generate.remote(rollout_id)) - logger.info(f"train: rollout {rollout_id} generate done") - - 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_rollout(args, rollout_id, rollout_data_ref, train_groups, should_save) - - 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() - - if should_run_periodic_action(rollout_id, args.eval_interval, num_rollout_per_epoch): - ray.get(rollout_manager.eval.remote(rollout_id)) - - ray.get(rollout_manager.dispose.remote()) - - -if __name__ == "__main__": - # Ensure stdout is line-buffered so nohup logs show progress immediately. - sys.stdout.reconfigure(line_buffering=True) - args = parse_args() - train(args) From 5cedd470c77b33bb3fc62c6626d43410a9812b11 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Fri, 20 Nov 2026 21:42:48 +0000 Subject: [PATCH 7/7] refactor(fsdp): remove compute, the train step range and the wake_up guard, which nothing calls now They existed to split the critic's steps around a forward-only scoring call from train_dmd2.py. The scoring now runs inside the critic's one train call, so `FSDPTrainRayActor.compute` / `RayTrainGroup.async_compute`, the `optim_steps` range of `train`, and the awake check that kept a second `wake_up` in one wake from repointing the frozen models' host copies have no caller. The trunk keeps its `hooks` argument, which the forward-only pass uses. --- miles/backends/fsdp_utils/actor.py | 122 ++---------------- miles/ray/actor_group.py | 17 +-- .../backends/fsdp_utils/test_compute_hooks.py | 89 ------------- .../backends/fsdp_utils/test_sleep_wake.py | 79 ------------ .../fsdp_utils/test_train_input_hook.py | 21 +-- .../fsdp_utils/test_train_optim_steps.py | 74 ----------- .../fsdp_utils/test_train_output_handoff.py | 48 ++----- tests/fast/rollout/test_async_training.py | 2 +- tests/fast/rollout/test_placement_group.py | 12 +- 9 files changed, 35 insertions(+), 429 deletions(-) delete mode 100644 tests/fast/backends/fsdp_utils/test_compute_hooks.py delete mode 100644 tests/fast/backends/fsdp_utils/test_sleep_wake.py delete mode 100644 tests/fast/backends/fsdp_utils/test_train_optim_steps.py diff --git a/miles/backends/fsdp_utils/actor.py b/miles/backends/fsdp_utils/actor.py index 7720af8b9..1a70caf2d 100644 --- a/miles/backends/fsdp_utils/actor.py +++ b/miles/backends/fsdp_utils/actor.py @@ -157,7 +157,6 @@ def init(self, args: Namespace, role: str, with_ref: bool = False) -> int: # ty ] # Reference and teacher weights never change, so each sleep points them back at the host copies kept at wake. self.frozen_parameter_host_copies_by_model = {model: {} for model in self.frozen_models_to_sleep} - self.asleep = False # Force a sync to ensure sharding is complete and old memory is freed. torch.cuda.synchronize() @@ -247,14 +246,12 @@ def sleep(self) -> None: if self.ema_optimizer is not None: move_optimizer(self.ema_optimizer, "cpu") clear_memory() - self.asleep = True dist.barrier(group=get_gloo_group()) print_memory("after sleep DiT") @timer def wake_up(self) -> None: - # Waking twice would point the frozen models' host copies at their GPU parameters. - if not self.args.offload_train or not self.asleep: + if not self.args.offload_train: return for model in self.actor_models_to_sleep: @@ -265,7 +262,6 @@ def wake_up(self) -> None: move_optimizer(self.optimizer, "cuda") if self.ema_optimizer is not None: move_optimizer(self.ema_optimizer, "cuda") - self.asleep = False dist.barrier(group=get_gloo_group()) print_memory("after wake_up DiT") @@ -325,10 +321,7 @@ def _log_metrics(self, rollout_id: int, log_dict: dict[str, float], step: int) - ) ) - def train( # type: ignore[override] - self, rollout_id: int, rollout_data_ref, external_data, optim_steps: tuple[int, int] | None = None - ) -> Any: - """Train this rank's shard of the rollout: all of its optimizer steps, or the range ``optim_steps``.""" + def train(self, rollout_id: int, rollout_data_ref, external_data) -> Any: # type: ignore[override] if self.args.offload_train: self.wake_up() @@ -340,12 +333,9 @@ def train( # type: ignore[override] materialize_stored_tensors(rollout_data["train_data"], store=self._output_store) 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, optim_steps=optim_steps + rollout_id=rollout_id, rollout_data=rollout_data, external_data=external_data ) - # The EMA moves once per rollout, after its last step, whichever call trains that step. - if self.ema_optimizer is not None and ( - optim_steps is None or optim_steps[1] == self.args.num_steps_per_rollout - ): + if self.ema_optimizer is not None: self.ema_optimizer.step(self.global_step) train_metric_utils.log_perf_data_raw( @@ -357,102 +347,26 @@ def train( # type: ignore[override] # object store until the paired rank of a later group reads it. return Box(ray.put(train_output)) - def compute(self, rollout_id: int, rollout_data_ref, external_data, hooks_key: str) -> Any: - """Run the loss hub's ``(--loss-type, hooks_key)`` hooks forward-only on this rank's shard of the rollout. + 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()) - Their train-input selection, one no-grad forward per micro-batch and their train-output hook, whose return - value is boxed as train's is. Nothing trains: the optimizer, scheduler, EMA and step count stay. - """ - if self.args.offload_train: - self.wake_up() - - with inverse_timer("train_wait"), timer("compute"): - rollout_data = ray.get(rollout_data_ref[self.parallel_state.get_mesh("dp").get_local_rank()].inner) - if self.args.debug_rollout_only: - return - external_data = {role: ray.get(box.inner) for role, box in external_data.items()} - output = self._compute_core( - rollout_id=rollout_id, - rollout_data=rollout_data, - external_data=external_data, - hooks=get_loss_hooks(self.args, hooks_key), - ) - return Box(ray.put(output)) - - def _compute_core(self, rollout_id: int, rollout_data, external_data: dict[str, Any], hooks: LossHooks) -> Any: - """One no-grad forward per micro-batch of the pairs ``hooks.train_input`` keeps, then ``hooks.train_output``.""" train_pairs: list = rollout_data["train_data"] - loss_ctx = self._loss_context(rollout_id, external_data) - if hooks.train_input is not None: - train_pairs = hooks.train_input(loss_ctx, train_pairs) + if not train_pairs: + raise ValueError("rollout_data['train_data'] is empty") - micro_bs = self.args.micro_batch_size - num_optim_steps_per_rollout = self.args.num_steps_per_rollout - # Numbered past the training micro-batches of this rank's whole rollout, so no training forward shares a - # draw with these. - microbatch_schedule = build_microbatch_schedule( - num_pairs_per_optim_step=len(rollout_data["train_data"]) // num_optim_steps_per_rollout, - num_optim_steps_per_rollout=num_optim_steps_per_rollout, - micro_batch_size=micro_bs, - ) - microbatch_id = sum(len(microbatch_ranges) for microbatch_ranges in microbatch_schedule) - microbatch_ranges = [ - (pair_lo, min(pair_lo + micro_bs, len(train_pairs))) for pair_lo in range(0, len(train_pairs), micro_bs) - ] - train_output_inputs: list = [] - # The formula may emit metrics; nothing reduces or logs them here. - metrics = new_metric_buffer( - self.parallel_state.dp_group, loss_ctx.device, self.models, sigma_buckets=self.args.log_loss_sigma_bucket - ) - with torch.no_grad(): - legacy_pad_to_len = self._maybe_legacy_window_pad_len(train_pairs, microbatch_ranges) - for pair_lo, pair_hi in microbatch_ranges: - self._forward_train_pair_batch( - loss_ctx, - train_pairs[pair_lo:pair_hi], - microbatch_id=microbatch_id, - optim_step_idx=num_optim_steps_per_rollout - 1, - train_output_inputs=train_output_inputs, - metrics=metrics, - pad_to_len=legacy_pad_to_len, - hooks=hooks, - ) - microbatch_id += 1 - # A no-grad forward leaves FSDP's root parameters gathered; sleep must move the shards. - for model in (*self.models.values(), *self.reference_models.values()): - reshard_model(model) - if hooks.train_output is None: - return None - return hooks.train_output(loss_ctx, train_pairs, train_output_inputs) - - def _loss_context(self, rollout_id: int, external_data: dict[str, Any]) -> DiffusionLossContext: - return DiffusionLossContext( + loss_ctx = DiffusionLossContext( models=self.models, reference_models=self.reference_models, train_pipeline_config=self.train_pipeline_config, sde_backend=self.sde_backend, args=self.args, forward_dtype=self._forward_dtype, - device=torch.device("cuda", torch.cuda.current_device()), + device=device, rollout_id=rollout_id, dp_rank=self.parallel_state.dp_rank, external_data=external_data, ) - - def _train_core( - self, - rollout_id: int, - rollout_data, - external_data: dict[str, Any], - optim_steps: tuple[int, int] | None = None, - ) -> Any: - """Run the shared diffusion training loop; ``optim_steps`` limits it to a range of the rollout's steps.""" - train_pairs: list = rollout_data["train_data"] - if not train_pairs: - raise ValueError("rollout_data['train_data'] is empty") - - loss_ctx = self._loss_context(rollout_id, external_data) - device = loss_ctx.device 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 @@ -484,14 +398,6 @@ def _train_core( microbatch_schedule=microbatch_schedule, ) - step_lo, step_hi = (0, num_optim_steps_per_rollout) if optim_steps is None else optim_steps - if not 0 <= step_lo < step_hi <= num_optim_steps_per_rollout: - raise ValueError( - f"optim_steps={optim_steps} is not a range within the {num_optim_steps_per_rollout} steps" - ) - if optim_steps is not None and self.args.diffusion_recompute_old_log_prob: - raise ValueError("--diffusion-recompute-old-log-prob recomputes the whole rollout; no step range") - # ------------- 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(): @@ -522,12 +428,10 @@ def _train_core( # ------------- Forward / Backward ------------- with timer("actor_train"): - # The micro-batch ids of the full run, so a range draws the same noise as the whole rollout would. - microbatch_id = sum(len(microbatch_ranges) for microbatch_ranges in microbatch_schedule[:step_lo]) + microbatch_id = 0 # past the training ids: no draw shared with a training forward forward_only_microbatch_id = sum(len(microbatch_ranges) for microbatch_ranges in microbatch_schedule) - for optim_step_idx in range(step_lo, step_hi): - microbatch_ranges = microbatch_schedule[optim_step_idx] + for optim_step_idx, microbatch_ranges in enumerate(microbatch_schedule): self.optimizer.zero_grad(set_to_none=True) old_log_prob_from_new = self.args.diffusion_recompute_old_log_prob and optim_step_idx == 0 diff --git a/miles/ray/actor_group.py b/miles/ray/actor_group.py index 3026bac08..3cb749b3f 100644 --- a/miles/ray/actor_group.py +++ b/miles/ray/actor_group.py @@ -100,23 +100,12 @@ 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, external_data=None, optim_steps=None): - """Train the rollout, or the range ``optim_steps`` of its optimizer steps; rank i receives rank i's output - of each group in ``external_data``.""" + 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()}, optim_steps - ) - for rank, actor in enumerate(self._actor_handlers) - ] - - def async_compute(self, rollout_id, rollout_data_ref, external_data, hooks_key): - """Run the loss hub's ``hooks_key`` hooks forward-only on each rank's shard; ``external_data`` as in - ``async_train``.""" - return [ - actor.compute.remote( - rollout_id, rollout_data_ref, {role: refs[rank] for role, refs in external_data.items()}, hooks_key + rollout_id, rollout_data_ref, {role: refs[rank] for role, refs in external_data.items()} ) for rank, actor in enumerate(self._actor_handlers) ] diff --git a/tests/fast/backends/fsdp_utils/test_compute_hooks.py b/tests/fast/backends/fsdp_utils/test_compute_hooks.py deleted file mode 100644 index 27643f52e..000000000 --- a/tests/fast/backends/fsdp_utils/test_compute_hooks.py +++ /dev/null @@ -1,89 +0,0 @@ -"""_compute_core runs a hook set forward-only over the pairs its train-input hook keeps, numbered past the rollout's -training micro-batches, and hands the train-output hook what the forwards kept; nothing trains. - - rollout pairs ──train_input──► kept pairs ──► one no-grad forward per micro-batch, ids after the training ones - ──► reshard the models ──► train_output(ctx, kept pairs, the one list) -""" - -from tests.ci.ci_register import register_cpu_ci - -register_cpu_ci(est_time=5, suite="stage-a-cpu", labels=["fsdp"]) - -import ast -from contextlib import nullcontext -from pathlib import Path -from typing import Any - -import torch -from tests.fast.backends.fsdp_utils.test_train_input_hook import _actor - -from miles.backends.fsdp_utils.loss_hub import LossHooks -from miles.utils.train_data_utils import build_microbatch_schedule - - -def _load_compute_core(resharded): - 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 == "_compute_core" - ) - namespace = dict( - Any=Any, - LossHooks=LossHooks, - torch=torch, - build_microbatch_schedule=build_microbatch_schedule, - timer=lambda name: nullcontext(), - new_metric_buffer=lambda *args, **kwargs: "metrics", - reshard_model=resharded.append, - ) - exec(compile(ast.Module(body=[method], type_ignores=[]), str(path), "exec"), namespace) - return namespace["_compute_core"] - - -def test_the_kept_pairs_forward_once_each_after_the_training_numbers(): - pairs = [{"sample_index": index} for index in range(6)] - forwarded, resharded, hooks_seen = [], [], [] - actor = _actor(None, None, forwarded) - actor.args.num_steps_per_rollout = 3 - actor.models = {"transformer": "critic"} - actor.reference_models = {"transformer": "reference"} - recorder = actor._forward_train_pair_batch - actor._forward_train_pair_batch = lambda ctx, chunk, **kwargs: ( - hooks_seen.append(kwargs["hooks"]), - recorder(ctx, chunk, **kwargs), - ) - hooks = LossHooks( - prepare=None, - formula=None, - train_input=lambda ctx, train_pairs: train_pairs[4:], - train_output=lambda ctx, train_pairs, inputs: (ctx.external_data, train_pairs, inputs), - ) - - output = _load_compute_core(resharded)( - actor, rollout_id=2, rollout_data={"train_data": pairs}, external_data={"scores": 1}, hooks=hooks - ) - - # Six training micro-batches (3 steps x 2) come first; the two kept pairs forward as 6 and 7, "at" the last step. - assert forwarded == [(6, 2, False, [pairs[4]]), (7, 2, False, [pairs[5]])] - assert hooks_seen == [hooks, hooks] - assert output == ({"scores": 1}, pairs[4:], [6, 7]) - assert resharded == ["critic", "reference"] - assert actor.global_step == 0 - - -def test_without_hooks_nothing_is_selected_or_returned(): - pairs = [{"sample_index": index} for index in range(2)] - forwarded, resharded = [], [] - actor = _actor(None, None, forwarded) - actor.args.num_steps_per_rollout = 1 - - output = _load_compute_core(resharded)( - actor, rollout_id=0, rollout_data={"train_data": pairs}, external_data={}, hooks=LossHooks(None, None) - ) - - assert forwarded == [(2, 0, False, [pairs[0]]), (3, 0, False, [pairs[1]])] - assert output is None diff --git a/tests/fast/backends/fsdp_utils/test_sleep_wake.py b/tests/fast/backends/fsdp_utils/test_sleep_wake.py deleted file mode 100644 index b783cc787..000000000 --- a/tests/fast/backends/fsdp_utils/test_sleep_wake.py +++ /dev/null @@ -1,79 +0,0 @@ -"""wake_up moves a sleeping group's models and optimizers once; a second wake_up before sleep does nothing. - -Consecutive train or compute calls of one group skip the sleep in between, and waking a frozen model twice would replace its host -copies with its GPU parameters, so the next sleep would leave it on the GPU. -""" - -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 pathlib import Path -from types import SimpleNamespace - - -def _load_sleep_and_wake_up(moves): - 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" - ) - methods = [ - node for node in actor_class.body if isinstance(node, ast.FunctionDef) and node.name in ("sleep", "wake_up") - ] - namespace = dict( - timer=lambda fn: fn, - print_memory=lambda name: None, - clear_memory=lambda: None, - get_gloo_group=lambda: None, - dist=SimpleNamespace(barrier=lambda group: None), - move_model=lambda model, device: moves.append(("model", model, device)), - sleep_frozen_model=lambda model, host_copies: moves.append(("frozen", model, "cpu")), - wake_up_frozen_model=lambda model, host_copies: moves.append(("frozen", model, "cuda")), - move_optimizer=lambda optimizer, device: moves.append(("optimizer", optimizer, device)), - ) - exec(compile(ast.Module(body=methods, type_ignores=[]), str(path), "exec"), namespace) - return namespace["sleep"], namespace["wake_up"] - - -def _actor(): - return SimpleNamespace( - args=Namespace(offload_train=True, fsdp_cpu_offload=False), - actor_models_to_sleep=["student"], - frozen_models_to_sleep=["teacher"], - frozen_parameter_host_copies_by_model={"teacher": {}}, - optimizer=SimpleNamespace(zero_grad=lambda set_to_none: None), - ema_optimizer=None, - asleep=False, - ) - - -def test_wake_up_moves_once_until_the_next_sleep(): - moves = [] - sleep, wake_up = _load_sleep_and_wake_up(moves) - actor = _actor() - - sleep(actor) - wake_up(actor) - wake_up(actor) - sleep(actor) - - to_cpu = [("model", "student", "cpu"), ("frozen", "teacher", "cpu"), ("optimizer", actor.optimizer, "cpu")] - to_cuda = [("model", "student", "cuda"), ("frozen", "teacher", "cuda"), ("optimizer", actor.optimizer, "cuda")] - assert moves == to_cpu + to_cuda + to_cpu - assert actor.asleep - - -def test_wake_up_without_offload_does_nothing(): - moves = [] - _, wake_up = _load_sleep_and_wake_up(moves) - actor = _actor() - actor.args.offload_train = False - actor.asleep = True - - wake_up(actor) - - assert moves == [] 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 3581dc40d..3da1d111c 100644 --- a/tests/fast/backends/fsdp_utils/test_train_input_hook.py +++ b/tests/fast/backends/fsdp_utils/test_train_input_hook.py @@ -25,6 +25,7 @@ from types import SimpleNamespace from typing import Any +import pytest import torch from miles.backends.fsdp_utils.loss_hub.types import DiffusionLossContext @@ -56,7 +57,7 @@ def _load_train_core(): def _actor(train_input, train_output, forwarded, **args): lists = [] # the train_output_inputs object each forward received - actor = SimpleNamespace( + return SimpleNamespace( lists=lists, models={}, reference_models={}, @@ -86,19 +87,11 @@ def _actor(train_input, train_output, forwarded, **args): ), _log_metrics=lambda rollout_id, metrics, step: None, ) - actor._loss_context = lambda rollout_id, external_data: DiffusionLossContext( - models=actor.models, - reference_models=actor.reference_models, - train_pipeline_config=None, - sde_backend=None, - args=actor.args, - forward_dtype=torch.float32, - device=torch.device("cpu"), - rollout_id=rollout_id, - dp_rank=0, - external_data=external_data, - ) - return actor + + +@pytest.fixture(autouse=True) +def _cpu_device(monkeypatch): + monkeypatch.setattr(torch.cuda, "current_device", lambda: 0) def test_later_stages_see_the_preprocessed_pairs(): diff --git a/tests/fast/backends/fsdp_utils/test_train_optim_steps.py b/tests/fast/backends/fsdp_utils/test_train_optim_steps.py deleted file mode 100644 index b07ef5b9e..000000000 --- a/tests/fast/backends/fsdp_utils/test_train_optim_steps.py +++ /dev/null @@ -1,74 +0,0 @@ -"""A train call may cover a range of the rollout's optimizer steps; the rollout's EMA step follows its last step. - - train(optim_steps=(lo, hi)) ──► _train_core trains windows lo..hi-1 with the micro-batch ids of the full run - (the earlier windows' micro-batches are counted, not run) - a range outside the schedule, or one under --diffusion-recompute-old-log-prob ──► ValueError - ema_optimizer.step ──► once per rollout, by the call whose range ends at the last step (or trains them all) -""" - -from tests.ci.ci_register import register_cpu_ci - -register_cpu_ci(est_time=5, suite="stage-a-cpu", labels=["fsdp"]) - -from types import SimpleNamespace - -import pytest -from tests.fast.backends.fsdp_utils.test_train_input_hook import _actor, _load_train_core -from tests.fast.backends.fsdp_utils.test_train_output_handoff import _load_methods - -from miles.utils.ray_utils import Box - - -def test_a_step_range_trains_those_steps_only(): - pairs = [{"sample_index": index} for index in range(6)] - forwarded = [] - actor = _actor(None, None, forwarded) - actor.args.num_steps_per_rollout = 3 - - _load_train_core()(actor, rollout_id=0, rollout_data={"train_data": pairs}, external_data={}, optim_steps=(1, 3)) - - # Windows 1 and 2: micro-batches 2..5, numbered as in the full run. - assert forwarded == [(index, index // 2, False, [pair]) for index, pair in enumerate(pairs)][2:] - assert actor.global_step == 2 - - -@pytest.mark.parametrize("optim_steps", [(1, 3), (1, 1), (-1, 1)]) -def test_a_step_range_outside_the_schedule_is_rejected(optim_steps): - pairs = [{"sample_index": index} for index in range(4)] - with pytest.raises(ValueError, match="not a range within the 2 steps"): - _load_train_core()( - _actor(None, None, []), - rollout_id=0, - rollout_data={"train_data": pairs}, - external_data={}, - optim_steps=optim_steps, - ) - - -def test_a_step_range_cannot_recompute_old_log_probs(): - pairs = [{"sample_index": index} for index in range(4)] - actor = _actor(None, None, [], diffusion_recompute_old_log_prob=True) - with pytest.raises(ValueError, match="no step range"): - _load_train_core()( - actor, rollout_id=0, rollout_data={"train_data": pairs}, external_data={}, optim_steps=(0, 1) - ) - - -@pytest.mark.parametrize( - ("optim_steps", "ema_steps"), - [(None, 1), ((0, 2), 0), ((2, 3), 1), ((0, 3), 1)], -) -def test_the_ema_steps_once_per_rollout_after_its_last_step(optim_steps, ema_steps): - namespace, store, put = _load_methods("train") - ema_calls = [] - actor = SimpleNamespace( - args=SimpleNamespace(offload_train=False, debug_rollout_only=False, num_steps_per_rollout=3), - ema_optimizer=SimpleNamespace(step=ema_calls.append), - global_step=7, - _train_core=lambda rollout_id, rollout_data, external_data, optim_steps: None, - parallel_state=SimpleNamespace(get_mesh=lambda name: SimpleNamespace(get_local_rank=lambda: 0)), - ) - - namespace["train"](actor, 0, [Box(put({"train_data": []}))], {}, optim_steps) - - assert ema_calls == [7] * ema_steps diff --git a/tests/fast/backends/fsdp_utils/test_train_output_handoff.py b/tests/fast/backends/fsdp_utils/test_train_output_handoff.py index fb763d31f..782bc02f2 100644 --- a/tests/fast/backends/fsdp_utils/test_train_output_handoff.py +++ b/tests/fast/backends/fsdp_utils/test_train_output_handoff.py @@ -1,4 +1,4 @@ -"""FSDPTrainRayActor.train and .compute hand their output to later groups through the object store, not the driver.""" +"""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 @@ -13,17 +13,15 @@ from miles.utils.ray_utils import Box -def _load_methods(*names): - """The named FSDPTrainRayActor methods, compiled with Ray, the timers and the perf log replaced.""" +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" ) - methods = [node for node in actor_class.body if isinstance(node, ast.FunctionDef) and node.name in names] - for method in methods: - method.decorator_list = [] + 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): @@ -39,18 +37,16 @@ def put(value): timer=lambda name: nullcontext(), inverse_timer=lambda name: nullcontext(), train_metric_utils=SimpleNamespace(log_perf_data_raw=lambda **kwargs: None), - get_loss_hooks=lambda args, hooks_key: ("hooks of", args.loss_type, hooks_key), ) - exec(compile(ast.Module(body=methods, type_ignores=[]), str(path), "exec"), namespace) - return namespace, store, put + 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(): - namespace, store, put = _load_methods("train") - train = namespace["train"] + train, store, put = _load_train() seen = {} - def train_core(rollout_id, rollout_data, external_data, optim_steps=None): + def train_core(rollout_id, rollout_data, external_data): seen.update(rollout_data=rollout_data, external_data=external_data) return {"scores": [rollout_id]} @@ -69,31 +65,3 @@ def train_core(rollout_id, rollout_data, external_data, optim_steps=None): assert isinstance(result, Box) assert store[result.inner] == {"scores": [3]} assert result.inner not in (shard.inner, critic_output.inner) - - -def test_compute_unboxes_external_data_and_boxes_its_output(): - namespace, store, put = _load_methods("compute") - seen = {} - - def compute_core(rollout_id, rollout_data, external_data, hooks): - seen.update(rollout_data=rollout_data, external_data=external_data, hooks=hooks) - return {"scores": [rollout_id]} - - actor = SimpleNamespace( - args=SimpleNamespace(offload_train=False, debug_rollout_only=False, loss_type="dmd2"), - _compute_core=compute_core, - parallel_state=SimpleNamespace(get_mesh=lambda name: SimpleNamespace(get_local_rank=lambda: 0)), - ) - shard = Box(put({"train_data": ["pair"]})) - critic_output = Box(put({"scores": [0]})) - - result = namespace["compute"](actor, 3, [shard], {"critic": critic_output}, "critic-scoring") - - assert seen == { - "rollout_data": {"train_data": ["pair"]}, - "external_data": {"critic": {"scores": [0]}}, - "hooks": ("hooks of", "dmd2", "critic-scoring"), - } - assert isinstance(result, Box) - assert store[result.inner] == {"scores": [3]} - assert result.inner not in (shard.inner, critic_output.inner) diff --git a/tests/fast/rollout/test_async_training.py b/tests/fast/rollout/test_async_training.py index 49c2cbd74..26d44c2e4 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, external_data, optim_steps=None): + 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() diff --git a/tests/fast/rollout/test_placement_group.py b/tests/fast/rollout/test_placement_group.py index 8db8b7311..5e1e0cdb6 100644 --- a/tests/fast/rollout/test_placement_group.py +++ b/tests/fast/rollout/test_placement_group.py @@ -115,19 +115,13 @@ 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)) - self.compute = SimpleNamespace(remote=lambda *args: (rank, "compute", *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"}, None), - (1, 7, "data", {"critic": "critic_1", "reward": "reward_1"}, None), - ] - assert group.async_train(7, "data") == [(0, 7, "data", {}, None), (1, 7, "data", {}, None)] - assert group.async_train(7, "data", optim_steps=(1, 3)) == [(0, 7, "data", {}, (1, 3)), (1, 7, "data", {}, (1, 3))] - assert group.async_compute(7, "data", external_data, "critic-scoring") == [ - (0, "compute", 7, "data", {"critic": "critic_0", "reward": "reward_0"}, "critic-scoring"), - (1, "compute", 7, "data", {"critic": "critic_1", "reward": "reward_1"}, "critic-scoring"), + (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", {})]