From df895c1ff3d6d2a9c32786398ec721e7c95e32e9 Mon Sep 17 00:00:00 2001 From: rockdu Date: Sun, 22 Nov 2026 22:23:55 -0800 Subject: [PATCH] refactor(fsdp): the teacher and the actor's extra forward each take their own input batch; the trunk stays flat --- docs/fsdp_model_roles.md | 4 +- docs/user-guide/cli-reference.md | 2 +- docs/user-guide/customization.md | 18 +-- miles/backends/fsdp_utils/actor.py | 108 ++++++++---------- miles/backends/fsdp_utils/loss_hub/dmd2.py | 72 +++++++----- miles/backends/fsdp_utils/loss_hub/types.py | 9 +- .../backends/fsdp_utils/test_loss_hub_dmd2.py | 99 ++++++++-------- .../fsdp_utils/test_reference_models.py | 43 ++++--- 8 files changed, 182 insertions(+), 173 deletions(-) diff --git a/docs/fsdp_model_roles.md b/docs/fsdp_model_roles.md index 2e07d85c9..b5d97f0e0 100644 --- a/docs/fsdp_model_roles.md +++ b/docs/fsdp_model_roles.md @@ -38,8 +38,8 @@ access `ctx.reference_models` by component name. A third source, the teacher (`--teacher-load`, with `--teacher-lora-adapter-path` for its adapters), is loaded by `--loss-type dmd2`, without adapters, into its critic group, which scores the student's samples with it. The actor runs it like the reference: on a micro-batch whose -prepare hook sets `PreparedBatch.teacher_guidance_scale`, the teacher's no-grad forward at that CFG -scale runs before the training forward, and the loss formula receives it as `teacher_pred`. +prepare hook sets `PreparedBatch.teacher_batch`, the teacher's no-grad forward on that input, at its +own CFG, runs before the training forward, and the loss formula receives it as `teacher_pred`. Each source may load pretrained PEFT LoRA adapters, one plain PEFT directory (what `save_pretrained` writes) per `--update-weight-target-module` entry, in the same order: diff --git a/docs/user-guide/cli-reference.md b/docs/user-guide/cli-reference.md index 2478d16cf..be4b3dc66 100644 --- a/docs/user-guide/cli-reference.md +++ b/docs/user-guide/cli-reference.md @@ -274,7 +274,7 @@ See [Dtype Control](../advanced/dtype-control.md). | `--ref-load` | str | – | HF pipeline checkpoint of an independent frozen reference model. Requires `--ref-mode ref`. | | `--ref-lora-adapter-path` | str+ | – | PEFT adapter directories applied to `--ref-load`, one per `--update-weight-target-module` entry, in order. | | `--ref-cpu-offload` | flag | off | Keep the reference shards in pinned CPU memory between forwards (FSDP `CPUOffloadPolicy`). | -| `--teacher-load` | str | – | HF pipeline checkpoint of a frozen teacher model; the actor runs it without grad on the micro-batches whose prepare hook sets `PreparedBatch.teacher_guidance_scale`, and `--loss-type dmd2` scores the student's samples with it. | +| `--teacher-load` | str | – | HF pipeline checkpoint of a frozen teacher model; the actor runs it without grad on the micro-batches whose prepare hook sets `PreparedBatch.teacher_batch`, and `--loss-type dmd2` scores the student's samples with it. | | `--teacher-lora-adapter-path` | str+ | – | PEFT adapter directories applied to `--teacher-load`, one per `--update-weight-target-module` entry, in order. | | `--teacher-cpu-offload` | flag | off | Keep the teacher shards in pinned CPU memory between forwards. | | `--custom-prepare-train-batch-path` | str | – | `custom_loss` only: builds DiT inputs. | diff --git a/docs/user-guide/customization.md b/docs/user-guide/customization.md index 916c0a158..808622f87 100644 --- a/docs/user-guide/customization.md +++ b/docs/user-guide/customization.md @@ -258,8 +258,8 @@ formula keeps the critic's x0 from that step's forward, before the update, next 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 its prepare hook also returns the -scoring batch, at a fresh draw, as `PreparedBatch.forward_only_batch`; the formula keeps the x0 of that -batch's forwards instead. +scoring batch, at a fresh draw, as the teacher's input and as `PreparedBatch.actor_forward_batch`, the critic's +own no-grad forward; the formula keeps the x0 of those two forwards instead. DiT forward always stays in the FSDP actor; the loss hook only computes the objective. @@ -297,11 +297,11 @@ counts from 0; the old-log-prob recompute of windows 1.. passes their training f `optim_step_idx` is its optimizer step; the built-in hooks seed their noise from `microbatch_id`. `PreparedBatch.latents`, `timesteps` and `timesteps_for_model` are keyed by latent stream name: `"visual"`, plus e.g. -`"audio"` for joint audio-video models. `PreparedBatch.teacher_guidance_scale` asks the trunk to run the frozen -teacher (`--teacher-load`) without grad on this micro-batch at that CFG scale, over `neg_cond` / `joint_cond`, before -the training forward; the formula receives it as `teacher_pred`. `PreparedBatch.forward_only_batch` is a second -prepared batch the trunk forwards without grad before this one, through the teacher it asks for and its model; a -formula whose prepare sets it also receives `forward_only_teacher_pred` and `forward_only_pred`. +`"audio"` for joint audio-video models. `PreparedBatch.teacher_batch` is the frozen teacher's input +(`--teacher-load`): a prepared batch with the teacher's own CFG fields and `neg_cond` / `joint_cond`, forwarded +without grad before the training forward; the formula receives it as `teacher_pred`. `PreparedBatch.actor_forward_batch` +is a second input for the model's own no-grad forward before the training forward; a formula whose prepare sets it also +receives that prediction as `actor_forward_pred`. The EMA and reference forwards always use the training batch. ### `--custom-loss-function-path` @@ -318,8 +318,8 @@ Read only under `--loss-type custom_loss`. `optim_step_idx` is the micro-batch's call. `new_pred`, `old_pred` and `ref_pred` are keyed by the same stream names as `prepared.latents`. `old_pred` (the EMA forward) is `None` for a custom formula, since the trunk runs it only under `--loss-type nft`; `ref_pred` is `None` with `--ref-mode none`. `teacher_pred` is the frozen teacher's -no-grad prediction at `prepared.teacher_guidance_scale`, which the trunk runs before the training forward when the -prepare hook sets that scale, else `None`. +no-grad prediction on `prepared.teacher_batch`, which the trunk runs before the training forward when the prepare +hook sets that batch, else `None`. ### `--custom-train-input-postprocess-path` diff --git a/miles/backends/fsdp_utils/actor.py b/miles/backends/fsdp_utils/actor.py index b20a838be..de1e254ee 100644 --- a/miles/backends/fsdp_utils/actor.py +++ b/miles/backends/fsdp_utils/actor.py @@ -530,88 +530,74 @@ def _forward_train_pair_batch( train_pipeline_config = self.train_pipeline_config forward_dtype = self._forward_dtype - def _forward_teacher_and_model(prepared): - """``prepared``'s DiT forward by model, the teacher prediction it asks for and its model's prediction.""" + def _model_inputs(batch_in) -> tuple: # Boundary dtypes are family policy; op interiors stay autocast-managed. - latents_in, timesteps_in, (pos_cond_in, neg_cond_in, joint_cond_in) = apply_input_dtype_policy( + return apply_input_dtype_policy( train_pipeline_config.input_dtype_policy, - latents=prepared.latents, - timesteps=prepared.timesteps_for_model, - conds=(prepared.pos_cond, prepared.neg_cond, prepared.joint_cond), + latents=batch_in.latents, + timesteps=batch_in.timesteps_for_model, + conds=(batch_in.pos_cond, batch_in.neg_cond, batch_in.joint_cond), default_dtype=forward_dtype, ) - def _compute_noise_pred( - model, - *, - use_cfg: bool = prepared.use_cfg, - cfg_batching: bool = prepared.cfg_batching, - guidance_scale: float = prepared.guidance_scale, - true_cfg_scale: float | None = prepared.true_cfg_scale, - ) -> dict[str, torch.Tensor]: - with torch.autocast( - "cuda", - dtype=forward_dtype, - enabled=forward_dtype != torch.float32 and train_pipeline_config.enable_autocast, - ): - return train_pipeline_config.compute_noise_pred( - model=model, - latents_input=latents_in, - timesteps_input=timesteps_in, - pos_cond=pos_cond_in, - neg_cond=neg_cond_in, - joint_cond=joint_cond_in, - use_cfg=use_cfg, - cfg_batching=cfg_batching, - guidance_scale=guidance_scale, - true_cfg_scale=true_cfg_scale, - ) + def _compute_noise_pred(model, batch_in, inputs: tuple) -> dict[str, torch.Tensor]: + latents_in, timesteps_in, (pos_cond_in, neg_cond_in, joint_cond_in) = inputs + with torch.autocast( + "cuda", + dtype=forward_dtype, + enabled=forward_dtype != torch.float32 and train_pipeline_config.enable_autocast, + ): + return train_pipeline_config.compute_noise_pred( + model=model, + latents_input=latents_in, + timesteps_input=timesteps_in, + pos_cond=pos_cond_in, + neg_cond=neg_cond_in, + joint_cond=joint_cond_in, + use_cfg=batch_in.use_cfg, + cfg_batching=batch_in.cfg_batching, + guidance_scale=batch_in.guidance_scale, + true_cfg_scale=batch_in.true_cfg_scale, + ) - # The frozen teacher runs before the training forward, so its gather never overlaps the activations. - teacher_pred = None - if prepared.teacher_guidance_scale is not None: - if prepared.component_name not in self.teacher_models: - raise ValueError("the prepared batch asks for a teacher forward, which needs --teacher-load") - teacher = self.teacher_models[prepared.component_name] - use_cfg = prepared.teacher_guidance_scale > 1.0 - with torch.no_grad(): - teacher_pred = _compute_noise_pred( - teacher, - use_cfg=use_cfg, - cfg_batching=use_cfg and train_pipeline_config.cfg_batching, - guidance_scale=prepared.teacher_guidance_scale, - true_cfg_scale=None, - ) - # A no-grad forward leaves FSDP's root parameters gathered; sleep must move the shards. - reshard_model(teacher) - return _compute_noise_pred, teacher_pred, _compute_noise_pred(prepared.model) + inputs = _model_inputs(prepared) - forward_only_preds = {} - if prepared.forward_only_batch is not None: + # The frozen teacher runs before the training forward, so its gather never overlaps the activations. + teacher_pred = None + if prepared.teacher_batch is not None: + teacher_batch = prepared.teacher_batch + if teacher_batch.component_name not in self.teacher_models: + raise ValueError("the prepared batch asks for a teacher forward, which needs --teacher-load") + teacher = self.teacher_models[teacher_batch.component_name] with torch.no_grad(): - _, forward_only_teacher_pred, forward_only_pred = _forward_teacher_and_model( - prepared.forward_only_batch + teacher_pred = _compute_noise_pred(teacher, teacher_batch, _model_inputs(teacher_batch)) + # A no-grad forward leaves FSDP's root parameters gathered; sleep must move the shards. + reshard_model(teacher) + + actor_forward_preds = {} + if prepared.actor_forward_batch is not None: + actor_forward_batch = prepared.actor_forward_batch + with torch.no_grad(): + actor_forward_preds["actor_forward_pred"] = _compute_noise_pred( + actor_forward_batch.model, actor_forward_batch, _model_inputs(actor_forward_batch) ) - forward_only_preds = dict( - forward_only_pred=forward_only_pred, forward_only_teacher_pred=forward_only_teacher_pred - ) - _compute_noise_pred, teacher_pred, new_pred = _forward_teacher_and_model(prepared) + new_pred = _compute_noise_pred(prepared.model, prepared, inputs) # pi_old: the latest EMA, also when an async batch was sampled with the EMA before it. old_pred = None if self.args.loss_type == "nft": with torch.no_grad(), self.ema_optimizer.use_weights(prepared.model): - old_pred = _compute_noise_pred(prepared.model) + old_pred = _compute_noise_pred(prepared.model, prepared, inputs) # KL reference. ref_pred = None if self.args.ref_mode == "ref": with torch.no_grad(): - ref_pred = _compute_noise_pred(self.reference_models[prepared.component_name]) + ref_pred = _compute_noise_pred(self.reference_models[prepared.component_name], prepared, inputs) elif self.args.ref_mode == "lora_base": with torch.no_grad(), prepared.model.disable_adapter(): - ref_pred = _compute_noise_pred(prepared.model) + ref_pred = _compute_noise_pred(prepared.model, prepared, inputs) # PEFT re-enables adapter gradients on exit; reshard first so that lands on the shards, not gathered copies. reshard_model(prepared.model) @@ -628,5 +614,5 @@ def _compute_noise_pred( train_output_inputs=train_output_inputs, write_old_log_prob=write_old_log_prob, old_log_prob_from_new=old_log_prob_from_new, - **forward_only_preds, + **actor_forward_preds, ) diff --git a/miles/backends/fsdp_utils/loss_hub/dmd2.py b/miles/backends/fsdp_utils/loss_hub/dmd2.py index 5d69aa6f4..67629905d 100644 --- a/miles/backends/fsdp_utils/loss_hub/dmd2.py +++ b/miles/backends/fsdp_utils/loss_hub/dmd2.py @@ -2,7 +2,7 @@ --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 draw and forward (the last step's forward-only batch) before the critic trains that step on them, as +separate draw and forward (the last step's actor-forward batch) before the critic trains that step on them, as tianweiy/DMD2 does. """ @@ -29,8 +29,8 @@ def prepare_critic_batch( """SFT flow matching on the student's x0 predictions, conditioned on their rollout prompts. The last step's samples are scored at their noisy inputs. Under --dmd2-critic-scoring reuse-critic-step that step - prepares the scoring batch: grid points from the scoring range, the teacher asked for. Under original it stays - plain SFT and carries the scoring batch as its forward-only batch. + prepares the scoring batch: grid points from the scoring range, the teacher's input alongside. Under original it + stays plain SFT and carries the scoring batch as the teacher's and the critic's actor-forward input. """ if _is_scoring_step(ctx, optim_step_idx): return prepare_scoring_batch( @@ -48,7 +48,11 @@ def prepare_critic_batch( optim_step_idx=optim_step_idx, pad_to_len=pad_to_len, ) - prepared = dataclasses.replace(prepared, forward_only_batch=scoring_batch) + prepared = dataclasses.replace( + prepared, + teacher_batch=scoring_batch.teacher_batch, + actor_forward_batch=dataclasses.replace(scoring_batch, teacher_batch=None), + ) return prepared @@ -60,8 +64,8 @@ def prepare_scoring_batch( 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.""" + """The critic's SFT draw on the student's x0 at grid points in --dmd2-score-sigma-range, with the teacher's + input at the same noisy inputs.""" prepared = prepare_sft_batch( ctx, _sft_batch(ctx, batch), @@ -70,7 +74,7 @@ def prepare_scoring_batch( pad_to_len=pad_to_len, grid_index_range=_score_grid_index_range(ctx), ) - return _request_teacher_forward(ctx, batch, prepared, pad_to_len=pad_to_len) + return dataclasses.replace(prepared, teacher_batch=_teacher_batch(ctx, batch, prepared, pad_to_len=pad_to_len)) def _sft_batch(ctx: DiffusionLossContext, batch: list[dict]) -> list[dict]: @@ -91,15 +95,18 @@ def _score_grid_index_range(ctx: DiffusionLossContext) -> tuple[int, int]: return round(num_train_timesteps * (1 - max_sigma)), round(num_train_timesteps * (1 - min_sigma)) -def _request_teacher_forward( +def _teacher_batch( ctx: DiffusionLossContext, batch: list[dict], prepared: PreparedBatch, *, pad_to_len: int | None ) -> PreparedBatch: - """Ask the trunk for the teacher at --dmd2-teacher-guidance-scale on this batch, with the rollout's negative + """The teacher's input: ``prepared``'s noisy latents at --dmd2-teacher-guidance-scale, with the rollout's negative cond collated for its CFG when the scale needs one.""" config = ctx.train_pipeline_config guidance_scale = ctx.args.dmd2_teacher_guidance_scale + unguided = dataclasses.replace( + prepared, use_cfg=False, cfg_batching=False, guidance_scale=guidance_scale, true_cfg_scale=None + ) if guidance_scale <= 1.0: - return dataclasses.replace(prepared, teacher_guidance_scale=guidance_scale) + return unguided envs = [pair["denoising_env"] for pair in batch] if any(env.neg_cond_kwargs is None for env in envs): raise ValueError( @@ -110,9 +117,9 @@ def _request_teacher_forward( neg_list = [config.prepare_cond_kwargs(env.neg_cond_kwargs, ctx.device) for env in envs] if config.cfg_batching: joint_cond = config.collate_cond_for_sample_batch(pos_list + neg_list, ctx.device, pad_to_len=pad_to_len) - return dataclasses.replace(prepared, joint_cond=joint_cond, teacher_guidance_scale=guidance_scale) + return dataclasses.replace(unguided, use_cfg=True, cfg_batching=True, joint_cond=joint_cond) neg_cond = config.collate_cond_for_sample_batch(neg_list, ctx.device, pad_to_len=pad_to_len) - return dataclasses.replace(prepared, neg_cond=neg_cond, teacher_guidance_scale=guidance_scale) + return dataclasses.replace(unguided, use_cfg=True, neg_cond=neg_cond) def critic_loss_formula( @@ -124,8 +131,7 @@ def critic_loss_formula( old_pred: dict[str, torch.Tensor] | None, ref_pred: dict[str, torch.Tensor] | None, teacher_pred: dict[str, torch.Tensor] | None = None, - forward_only_pred: dict[str, torch.Tensor] | None = None, - forward_only_teacher_pred: dict[str, torch.Tensor] | None = None, + actor_forward_pred: dict[str, torch.Tensor] | None = None, metrics: MetricBuffer, optim_step_idx: int, train_output_inputs: list, @@ -135,14 +141,14 @@ def critic_loss_formula( """The SFT loss in --dmd2-critic-loss-space. On the last step it also keeps the critic's and the teacher's x0 at each noisy input, before that step's update: - those of the training forward, or of the forward-only batch when the step carries one. + the critic's from the actor-forward batch when the step carries one, else from the training forward. """ - if _is_scoring_step(ctx, optim_step_idx): - keep_scores(batch, prepared, new_pred, teacher_pred, train_output_inputs) - elif prepared.forward_only_batch is not None: - keep_scores( - batch, prepared.forward_only_batch, forward_only_pred, forward_only_teacher_pred, train_output_inputs - ) + if teacher_pred is not None: + if actor_forward_pred is None: + fake_batch, fake_pred = prepared, new_pred + else: + fake_batch, fake_pred = prepared.actor_forward_batch, actor_forward_pred + keep_scores(batch, fake_batch, fake_pred, prepared.teacher_batch, 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))) @@ -167,17 +173,21 @@ def critic_loss_formula( def keep_scores( batch: list[dict], - prepared: PreparedBatch, - new_pred: dict[str, torch.Tensor], - teacher_pred: dict[str, torch.Tensor] | None, + fake_batch: PreparedBatch, + fake_pred: dict[str, torch.Tensor], + real_batch: PreparedBatch, + real_pred: dict[str, torch.Tensor], 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): + """Per sample, x0_fake = x_s - sigma v_critic and x0_real = x_s - sigma v_teacher, each at its own batch's + noisy input, for score_last_step_samples.""" + + def x0(prepared: PreparedBatch, pred: dict[str, torch.Tensor]) -> torch.Tensor: + latents = prepared.latents["visual"] + sigmas = prepared.extras["sigmas"]["visual"].view(len(batch), *([1] * (latents.ndim - 1))) + return latents - sigmas * pred["visual"].detach().float() + + for pair, real, fake in zip(batch, x0(real_batch, real_pred), x0(fake_batch, fake_pred), strict=True): train_output_inputs.append((pair["sample_index"], real, fake)) @@ -194,7 +204,7 @@ def _is_scoring_step(ctx: DiffusionLossContext, optim_step_idx: int) -> bool: 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.""" + """Under original the last step's samples are scored by an actor forward, before the critic trains that step.""" return ctx.args.dmd2_critic_scoring == "original" and optim_step_idx == ctx.args.num_steps_per_rollout - 1 diff --git a/miles/backends/fsdp_utils/loss_hub/types.py b/miles/backends/fsdp_utils/loss_hub/types.py index 169c829fe..c592acd7e 100644 --- a/miles/backends/fsdp_utils/loss_hub/types.py +++ b/miles/backends/fsdp_utils/loss_hub/types.py @@ -71,8 +71,7 @@ class PreparedBatch: joint_cond: dict | None advantage: torch.Tensor extras: dict[str, Any] = field(default_factory=dict) - # CFG scale of the frozen teacher's no-grad forward on this batch; None runs no teacher forward. - teacher_guidance_scale: float | None = None - # A second batch the trunk forwards without grad before this one: the teacher it asks for and its model. The - # formula receives them as ``forward_only_teacher_pred`` and ``forward_only_pred``. - forward_only_batch: PreparedBatch | None = None + # The frozen teacher's input, with its own CFG fields; its no-grad prediction reaches the formula as ``teacher_pred``. + teacher_batch: PreparedBatch | None = None + # A second input for the model's own no-grad forward; its prediction reaches the formula as ``actor_forward_pred``. + actor_forward_batch: PreparedBatch | None = None diff --git a/tests/fast/backends/fsdp_utils/test_loss_hub_dmd2.py b/tests/fast/backends/fsdp_utils/test_loss_hub_dmd2.py index aa742042a..106b10eea 100644 --- a/tests/fast/backends/fsdp_utils/test_loss_hub_dmd2.py +++ b/tests/fast/backends/fsdp_utils/test_loss_hub_dmd2.py @@ -7,8 +7,8 @@ whose samples get scored, draws grid points whose unshifted sigma lies in --dmd2-score-sigma-range, default [0.02, 0.98]) │ - the last step also asks the trunk for the teacher, PreparedBatch.teacher_guidance_scale, - with the rollout's neg cond collated for its CFG) + the last step also carries the teacher's input, PreparedBatch.teacher_batch, the same + noisy latents at --dmd2-teacher-guidance-scale with the rollout's neg cond for its CFG) │ the trunk runs the teacher without grad at x_s before the critic's training forward ──► v_real │ @@ -48,10 +48,10 @@ 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 carries the scoring batch, a fresh draw in the -scoring range, as its forward-only batch; the formula keeps the x0 of that batch's forwards: +scoring range, as the teacher's and the critic's actor-forward input; the formula keeps the x0 of those forwards: test_under_original_only_the_last_step_carries_a_scoring_batch_and_it_stays_plain_sft test_the_scoring_batch_is_the_reuse_last_step_batch_one_step_of_micro_batches_later - test_under_original_the_formula_keeps_the_x0_of_the_forward_only_batch + test_under_original_the_formula_keeps_the_x0_of_the_actor_forward_batch test_either_mode_scores_the_last_step_once by its training forward or before it, never both or neither """ @@ -164,33 +164,20 @@ def _forward(config, model, prepared, *, use_cfg, cfg_batching, guidance_scale): def _critic_step(ctx, pairs, optim_step_idx, train_output_inputs, metrics=None, teacher=None): - """One critic optimizer step as _train_core runs it: prepare, the forward-only batch it carries, the teacher - forward it asks for, the critic's training forward, the loss hook.""" + """One critic optimizer step as _train_core runs it: prepare, the teacher on its batch, the critic's no-grad + forward on the actor-forward batch, the training forward, the loss hook.""" config = ctx.train_pipeline_config teacher = _CondVelocity(1.0) if teacher is None else teacher - def forward_teacher_and_model(prepared): - teacher_pred = None - if prepared.teacher_guidance_scale is not None: - use_cfg = prepared.teacher_guidance_scale > 1.0 - with torch.no_grad(): - teacher_pred = _forward( - config, - teacher, - prepared, - use_cfg=use_cfg, - cfg_batching=use_cfg and config.cfg_batching, - guidance_scale=prepared.teacher_guidance_scale, - ) - new_pred = _forward( + def forward(model, prepared): + return _forward( config, - prepared.model, + model, prepared, use_cfg=prepared.use_cfg, cfg_batching=prepared.cfg_batching, guidance_scale=prepared.guidance_scale, ) - return teacher_pred, new_pred steps = [] for start in range(0, len(pairs), ctx.args.micro_batch_size): @@ -198,14 +185,15 @@ def forward_teacher_and_model(prepared): prepared = dmd2.prepare_critic_batch( ctx, batch, microbatch_id=optim_step_idx * 10 + start, optim_step_idx=optim_step_idx ) - forward_only_preds = {} - if prepared.forward_only_batch is not None: + teacher_pred = None + if prepared.teacher_batch is not None: with torch.no_grad(): - forward_only_teacher_pred, forward_only_pred = forward_teacher_and_model(prepared.forward_only_batch) - forward_only_preds = dict( - forward_only_pred=forward_only_pred, forward_only_teacher_pred=forward_only_teacher_pred - ) - teacher_pred, new_pred = forward_teacher_and_model(prepared) + teacher_pred = forward(teacher, prepared.teacher_batch) + actor_forward_preds = {} + if prepared.actor_forward_batch is not None: + with torch.no_grad(): + actor_forward_preds["actor_forward_pred"] = forward(prepared.model, prepared.actor_forward_batch) + new_pred = forward(prepared.model, prepared) loss = dmd2.critic_loss_formula( ctx, batch, @@ -217,7 +205,7 @@ def forward_teacher_and_model(prepared): metrics=metrics or _Metrics(), optim_step_idx=optim_step_idx, train_output_inputs=train_output_inputs, - **forward_only_preds, + **actor_forward_preds, ) steps.append((batch, prepared, new_pred, loss)) return steps @@ -344,7 +332,7 @@ def test_earlier_steps_ask_for_no_teacher(): ctx = _ctx(teacher_guidance_scale=3.0) for optim_step_idx in range(CRITIC_STEPS - 1): prepared = dmd2.prepare_critic_batch(ctx, _pairs(2), microbatch_id=0, optim_step_idx=optim_step_idx) - assert prepared.teacher_guidance_scale is None + assert prepared.teacher_batch is None assert prepared.neg_cond is None and prepared.joint_cond is None @@ -357,20 +345,29 @@ def test_last_step_asks_for_the_guided_teacher(cfg_batching): prepared = dmd2.prepare_critic_batch(ctx, pairs, microbatch_id=0, optim_step_idx=CRITIC_STEPS - 1) - assert prepared.teacher_guidance_scale == 3.0 + # The training batch stays unguided; the teacher's input carries the CFG and the negative cond. assert not prepared.use_cfg and not prepared.cfg_batching + assert prepared.neg_cond is None and prepared.joint_cond is None + teacher_batch = prepared.teacher_batch + assert torch.equal(teacher_batch.latents["visual"], prepared.latents["visual"]) + assert (teacher_batch.use_cfg, teacher_batch.cfg_batching, teacher_batch.guidance_scale) == ( + True, + cfg_batching, + 3.0, + ) + assert teacher_batch.true_cfg_scale is None pos_list = [config.prepare_cond_kwargs(pair["denoising_env"].pos_cond_kwargs, ctx.device) for pair in pairs] neg_list = [config.prepare_cond_kwargs(pair["denoising_env"].neg_cond_kwargs, ctx.device) for pair in pairs] pos = config.collate_cond_for_sample_batch(pos_list, ctx.device)["encoder_hidden_states"] - assert torch.equal(prepared.pos_cond["encoder_hidden_states"], pos) + assert torch.equal(teacher_batch.pos_cond["encoder_hidden_states"], pos) if cfg_batching: joint = config.collate_cond_for_sample_batch(pos_list + neg_list, ctx.device)["encoder_hidden_states"] - assert prepared.neg_cond is None - assert torch.equal(prepared.joint_cond["encoder_hidden_states"], joint) + assert teacher_batch.neg_cond is None + assert torch.equal(teacher_batch.joint_cond["encoder_hidden_states"], joint) else: neg = config.collate_cond_for_sample_batch(neg_list, ctx.device)["encoder_hidden_states"] - assert prepared.joint_cond is None - assert torch.equal(prepared.neg_cond["encoder_hidden_states"], neg) + assert teacher_batch.joint_cond is None + assert torch.equal(teacher_batch.neg_cond["encoder_hidden_states"], neg) def test_unguided_teacher_needs_no_negative_cond(): @@ -378,8 +375,9 @@ def test_unguided_teacher_needs_no_negative_cond(): prepared = dmd2.prepare_critic_batch( ctx, _pairs(2, with_neg=False), microbatch_id=0, optim_step_idx=CRITIC_STEPS - 1 ) - assert prepared.teacher_guidance_scale == 1.0 - assert prepared.neg_cond is None and prepared.joint_cond is None + teacher_batch = prepared.teacher_batch + assert (teacher_batch.use_cfg, teacher_batch.cfg_batching, teacher_batch.guidance_scale) == (False, False, 1.0) + assert teacher_batch.neg_cond is None and teacher_batch.joint_cond is None def test_teacher_cfg_needs_the_rollout_negative_cond(): @@ -645,10 +643,14 @@ def test_under_original_only_the_last_step_carries_a_scoring_batch_and_it_stays_ sft_batch = prepare_sft_batch(ctx, _sft_pairs(ctx, pairs), microbatch_id=6, 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 - assert critic_batch.forward_only_batch is not None - assert dmd2.prepare_critic_batch(ctx, pairs, microbatch_id=0, optim_step_idx=0).forward_only_batch is None + # The teacher and the critic's actor forward both run on the scoring draw. + assert torch.equal( + critic_batch.teacher_batch.latents["visual"], critic_batch.actor_forward_batch.latents["visual"] + ) + assert critic_batch.actor_forward_batch.teacher_batch is None + first_step = dmd2.prepare_critic_batch(ctx, pairs, microbatch_id=0, optim_step_idx=0) + assert first_step.teacher_batch is None and first_step.actor_forward_batch is None @pytest.mark.parametrize("cfg_batching", [False, True]) @@ -661,23 +663,22 @@ def test_the_scoring_batch_is_the_reuse_last_step_batch_one_step_of_micro_batche original_ctx = _original_ctx(num_microbatches_per_optim_step=3) original_ctx.train_pipeline_config.cfg_batching = cfg_batching # Micro-batch 6 of a step of 3: its scoring draw is micro-batch 9, past the last step's training ids. - scoring = dmd2.prepare_critic_batch( - original_ctx, pairs, microbatch_id=6, optim_step_idx=CRITIC_STEPS - 1 - ).forward_only_batch + original = dmd2.prepare_critic_batch(original_ctx, pairs, microbatch_id=6, optim_step_idx=CRITIC_STEPS - 1) + scoring = original.actor_forward_batch 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 + assert original.teacher_batch.guidance_scale == reuse.teacher_batch.guidance_scale == 3.0 for cond in ("pos_cond", "neg_cond", "joint_cond"): - reuse_cond, scoring_cond = getattr(reuse, cond), getattr(scoring, cond) + reuse_cond, scoring_cond = getattr(reuse.teacher_batch, cond), getattr(original.teacher_batch, 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_under_original_the_formula_keeps_the_x0_of_the_forward_only_batch(): +def test_under_original_the_formula_keeps_the_x0_of_the_actor_forward_batch(): ctx = _original_ctx(teacher_guidance_scale=1.0) ctx.models["transformer"] = _NoisyInputVelocity() pairs = _pairs(2) @@ -687,7 +688,7 @@ def test_under_original_the_formula_keeps_the_x0_of_the_forward_only_batch(): scores = dmd2.score_last_step_samples(ctx, pairs, inputs) assert list(scores) == [100, 101] - scoring = prepared.forward_only_batch + scoring = prepared.actor_forward_batch x_s = scoring.latents["visual"] sigma = scoring.extras["sigmas"]["visual"].view(-1, 1, 1, 1) critic_velocity = x_s + scoring.timesteps_for_model["visual"].view(-1, 1, 1, 1) diff --git a/tests/fast/backends/fsdp_utils/test_reference_models.py b/tests/fast/backends/fsdp_utils/test_reference_models.py index 1fa255d4e..72ea38924 100644 --- a/tests/fast/backends/fsdp_utils/test_reference_models.py +++ b/tests/fast/backends/fsdp_utils/test_reference_models.py @@ -171,12 +171,27 @@ def make_actor_forward_harness( cfg_batching=False, guidance_scale=1.0, true_cfg_scale=true_cfg_scale, - teacher_guidance_scale=teacher_guidance_scale, - forward_only_batch=None, + teacher_batch=None, + actor_forward_batch=None, ) + config = TinyPipelineConfig() def prepare(ctx, batch, **kwargs): observed["prepare_kwargs"] = kwargs + if teacher_guidance_scale is not None: + # The teacher's input: this batch at the teacher's CFG, as dmd2's prepare hook builds it. + use_cfg = teacher_guidance_scale > 1.0 + prepared.teacher_batch = SimpleNamespace( + **{ + **vars(prepared), + "use_cfg": use_cfg, + "cfg_batching": use_cfg and config.cfg_batching, + "guidance_scale": teacher_guidance_scale, + "true_cfg_scale": None, + "teacher_batch": None, + "actor_forward_batch": None, + } + ) return prepared def loss_formula(ctx, batch, prepared, *, new_pred, old_pred, ref_pred, teacher_pred, **kwargs): @@ -193,7 +208,7 @@ def loss_formula(ctx, batch, prepared, *, new_pred, old_pred, ref_pred, teacher_ model=torch.nn.ModuleDict(models), reference_models=reference_models, teacher_models={} if teacher_models is None else teacher_models, - train_pipeline_config=TinyPipelineConfig(), + train_pipeline_config=config, _forward_dtype=torch.float32, loss_hooks=SimpleNamespace(prepare=prepare, formula=loss_formula), ) @@ -599,25 +614,23 @@ def test_an_unguided_teacher_runs_without_cfg(): ) -def test_a_forward_only_batch_runs_without_grad_before_the_training_forward(): +def test_an_actor_forward_batch_runs_without_grad_before_the_training_forward(): harness, observed, actor, teacher = _teacher_harness(None) prepared = harness.loss_hooks.prepare(None, []) - forward_only_inputs = torch.full((2, 3), 2.0) - prepared.forward_only_batch = SimpleNamespace( - **{**vars(prepared), "latents": {"visual": forward_only_inputs}, "teacher_guidance_scale": 1.0} - ) + other_inputs = torch.full((2, 3), 2.0) + other = {**vars(prepared), "latents": {"visual": other_inputs}, "teacher_batch": None, "actor_forward_batch": None} + prepared.actor_forward_batch = SimpleNamespace(**other) + prepared.teacher_batch = SimpleNamespace(**other) _run_forward(harness, reshard_model=lambda model: None).backward() - # Its teacher and its model, then the training forward, which asked for no teacher. + # The teacher on its batch, the model on the actor-forward batch, then the training forward. assert observed["order"] == ["teacher", "actor", "actor"] - assert "teacher_pred" not in observed - forward_only_pred = observed["formula_kwargs"]["forward_only_pred"]["visual"] - forward_only_teacher_pred = observed["formula_kwargs"]["forward_only_teacher_pred"]["visual"] - assert not forward_only_pred.requires_grad and not forward_only_teacher_pred.requires_grad + actor_forward_pred = observed["formula_kwargs"]["actor_forward_pred"]["visual"] + assert not actor_forward_pred.requires_grad and not observed["teacher_pred"].requires_grad with torch.no_grad(): - torch.testing.assert_close(forward_only_pred, actor(forward_only_inputs)) - torch.testing.assert_close(forward_only_teacher_pred, teacher(forward_only_inputs)) + torch.testing.assert_close(actor_forward_pred, actor(other_inputs)) + torch.testing.assert_close(observed["teacher_pred"], teacher(other_inputs)) torch.testing.assert_close(observed["new_pred"], actor(torch.ones(2, 3)))