diff --git a/docs/user-guide/cli-reference.md b/docs/user-guide/cli-reference.md index e249f433a..2478d16cf 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). | | `--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 d4eed2185..f32af1eb7 100644 --- a/docs/user-guide/customization.md +++ b/docs/user-guide/customization.md @@ -257,6 +257,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. +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/miles/backends/fsdp_utils/actor.py b/miles/backends/fsdp_utils/actor.py index b948f444c..1a70caf2d 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, 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 @@ -429,6 +429,8 @@ def _train_core(self, rollout_id: int, rollout_data, external_data: dict[str, An # ------------- Forward / Backward ------------- with timer("actor_train"): 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, microbatch_ranges in enumerate(microbatch_schedule): self.optimizer.zero_grad(set_to_none=True) @@ -447,6 +449,22 @@ def _train_core(self, rollout_id: int, rollout_data, external_data: dict[str, An 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( @@ -519,10 +537,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 | ForwardOnlyHooks | 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 @@ -600,7 +620,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/backends/fsdp_utils/loss_hub/__init__.py b/miles/backends/fsdp_utils/loss_hub/__init__.py index 651570b37..2eb882cc6 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, + is_scored_before_training, 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 @@ -23,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) @@ -35,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] = { @@ -49,7 +66,12 @@ 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), + ("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), + ), } diff --git a/miles/backends/fsdp_utils/loss_hub/dmd2.py b/miles/backends/fsdp_utils/loss_hub/dmd2.py index 371679c19..f5a031f9c 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's ``forward_only`` hooks) 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]: @@ -133,7 +192,13 @@ def score_last_step_samples( 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 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]: diff --git a/miles/utils/arguments.py b/miles/utils/arguments.py index d943d311c..b573e9bc4 100644 --- a/miles/utils/arguments.py +++ b/miles/utils/arguments.py @@ -1061,6 +1061,16 @@ 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.", + ) 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..9a1bcb2f0 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 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_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 @@ -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,94 @@ 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)) + + +@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() + ctx.args.dmd2_critic_scoring = critic_scoring + + 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 0f1019464..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,11 +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 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 @@ -21,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 @@ -47,6 +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", + 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", + ), ), } @@ -67,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 e90e271a2..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,8 @@ 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, ) exec(compile(ast.Module(body=[method], type_ignores=[]), str(path), "exec"), namespace) @@ -531,6 +533,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_input_hook.py b/tests/fast/backends/fsdp_utils/test_train_input_hook.py index b01bf3384..3da1d111c 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. @@ -73,7 +74,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, @@ -149,3 +150,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]