diff --git a/docs/fsdp_model_roles.md b/docs/fsdp_model_roles.md index 684039068..2e07d85c9 100644 --- a/docs/fsdp_model_roles.md +++ b/docs/fsdp_model_roles.md @@ -37,8 +37,9 @@ access `ctx.reference_models` by component name. A third source, the teacher (`--teacher-load`, with `--teacher-lora-adapter-path` for its adapters), is loaded by `--loss-type dmd2`, without adapters, into its critic group, which -scores the student's samples with it. Otherwise only a custom hook reads it, from `ctx.teacher_models`, -and teacher inference should run inside `torch.no_grad()`. +scores the student's samples with it. The actor runs it like the reference: on a micro-batch whose +prepare hook sets `PreparedBatch.teacher_guidance_scale`, the teacher's no-grad forward at that CFG +scale runs before the training forward, and the loss formula receives it as `teacher_pred`. Each source may load pretrained PEFT LoRA adapters, one plain PEFT directory (what `save_pretrained` writes) per `--update-weight-target-module` entry, in the same order: diff --git a/docs/user-guide/cli-reference.md b/docs/user-guide/cli-reference.md index 4916f691a..c0635f9ef 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, offered to the hooks as `ctx.teacher_models`; `--loss-type dmd2` scores the student's samples with it. | +| `--teacher-load` | str | – | HF pipeline checkpoint of a frozen teacher model; the actor runs it without grad on the micro-batches whose prepare hook sets `PreparedBatch.teacher_guidance_scale`, and `--loss-type dmd2` scores the student's samples with it. | | `--teacher-lora-adapter-path` | str+ | – | PEFT adapter directories applied to `--teacher-load`, one per `--update-weight-target-module` entry, in order. | | `--teacher-cpu-offload` | flag | off | Keep the teacher shards in pinned CPU memory between forwards. | | `--custom-prepare-train-batch-path` | str | – | `custom_loss` only: builds DiT inputs. | diff --git a/docs/user-guide/customization.md b/docs/user-guide/customization.md index 3a5f30314..09e7465f9 100644 --- a/docs/user-guide/customization.md +++ b/docs/user-guide/customization.md @@ -248,9 +248,9 @@ flags (`--custom-prepare-train-batch-path`, `--custom-loss-function-path`, falls back to the Flow-GRPO built-in. `dmd2` also trains a `critic` group before the actor on each rollout: it starts from `--critic-load` (default `--teacher-load`), learns the student's samples with the SFT loss at `--critic-lr` (default `--lr`). -On its last step it keeps its own x0 predictions from that step's forward, before the update, and -after training its train-output hook hands them with the teacher's x0 at the same noisy inputs to the -actor as `ctx.external_data["critic"]`. The actor trains on those samples only (its train-input hook): +On its last step its prepare hook also asks for the teacher at the same noisy inputs, and its loss +formula keeps the critic's x0 from that step's forward, before the update, next to the teacher's; after +training its train-output hook hands them to the actor as `ctx.external_data["critic"]`. The actor trains on those samples only (its train-input hook): it recomputes the student's x0 at the rollout's step and moves it along their difference. DiT forward always stays in the FSDP actor; the loss hook only computes the @@ -289,13 +289,16 @@ counts from 0; the old-log-prob recompute of windows 1.. passes their training f `optim_step_idx` is its optimizer step; the built-in hooks seed their noise from `microbatch_id`. `PreparedBatch.latents`, `timesteps` and `timesteps_for_model` are keyed by latent stream name: `"visual"`, plus e.g. -`"audio"` for joint audio-video models. +`"audio"` for joint audio-video models. `PreparedBatch.teacher_guidance_scale` asks the trunk to run the frozen +teacher (`--teacher-load`) without grad on this micro-batch at that CFG scale, over `neg_cond` / `joint_cond`, before +the training forward; the formula receives it as `teacher_pred`. ### `--custom-loss-function-path` ```python def loss_formula( - ctx, batch, prepared, *, new_pred, old_pred, ref_pred, metrics, optim_step_idx, train_output_inputs, **kwargs + ctx, batch, prepared, *, new_pred, old_pred, ref_pred, teacher_pred, metrics, optim_step_idx, + train_output_inputs, **kwargs ): ... ``` @@ -304,7 +307,9 @@ Read only under `--loss-type custom_loss`. `optim_step_idx` is the micro-batch's `train_output_inputs` is the list the formula may fill for the train-output hook, empty at the start of each train call. `new_pred`, `old_pred` and `ref_pred` are keyed by the same stream names as `prepared.latents`. `old_pred` (the EMA forward) is `None` for a custom formula, since the trunk runs it -only under `--loss-type nft`; `ref_pred` is `None` with `--ref-mode none`. +only under `--loss-type nft`; `ref_pred` is `None` with `--ref-mode none`. `teacher_pred` is the frozen teacher's +no-grad prediction at `prepared.teacher_guidance_scale`, which the trunk runs before the training forward when the +prepare hook sets that scale, else `None`. ### `--custom-train-input-postprocess-path` diff --git a/miles/backends/fsdp_utils/actor.py b/miles/backends/fsdp_utils/actor.py index d296992a4..b948f444c 100644 --- a/miles/backends/fsdp_utils/actor.py +++ b/miles/backends/fsdp_utils/actor.py @@ -358,7 +358,6 @@ def _train_core(self, rollout_id: int, rollout_data, external_data: dict[str, An loss_ctx = DiffusionLossContext( models=self.models, reference_models=self.reference_models, - teacher_models=self.teacher_models, train_pipeline_config=self.train_pipeline_config, sde_backend=self.sde_backend, args=self.args, @@ -538,7 +537,14 @@ def _forward_train_pair_batch( default_dtype=forward_dtype, ) - def _compute_noise_pred(model) -> dict[str, torch.Tensor]: + def _compute_noise_pred( + model, + *, + use_cfg: bool = prepared.use_cfg, + cfg_batching: bool = prepared.cfg_batching, + guidance_scale: float = prepared.guidance_scale, + true_cfg_scale: float | None = prepared.true_cfg_scale, + ) -> dict[str, torch.Tensor]: with torch.autocast( "cuda", dtype=forward_dtype, @@ -551,12 +557,30 @@ def _compute_noise_pred(model) -> dict[str, torch.Tensor]: pos_cond=pos_cond_in, neg_cond=neg_cond_in, joint_cond=joint_cond_in, - use_cfg=prepared.use_cfg, - cfg_batching=prepared.cfg_batching, - guidance_scale=prepared.guidance_scale, - true_cfg_scale=prepared.true_cfg_scale, + use_cfg=use_cfg, + cfg_batching=cfg_batching, + guidance_scale=guidance_scale, + true_cfg_scale=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) + new_pred = _compute_noise_pred(prepared.model) # pi_old: the latest EMA, also when an async batch was sampled with the EMA before it. @@ -583,6 +607,7 @@ def _compute_noise_pred(model) -> dict[str, torch.Tensor]: new_pred=new_pred, old_pred=old_pred, ref_pred=ref_pred, + teacher_pred=teacher_pred, metrics=metrics, optim_step_idx=optim_step_idx, train_output_inputs=train_output_inputs, diff --git a/miles/backends/fsdp_utils/loss_hub/dmd2.py b/miles/backends/fsdp_utils/loss_hub/dmd2.py index 2388cd17f..371679c19 100644 --- a/miles/backends/fsdp_utils/loss_hub/dmd2.py +++ b/miles/backends/fsdp_utils/loss_hub/dmd2.py @@ -6,8 +6,6 @@ import torch -from miles.backends.fsdp_utils.ema import reshard_model -from miles.backends.fsdp_utils.input_dtype_policy import apply_input_dtype_policy from miles.backends.fsdp_utils.loss_hub.sft import prepare_sft_batch, sft_loss_formula from miles.backends.fsdp_utils.loss_hub.types import DiffusionLossContext, PreparedBatch from miles.backends.fsdp_utils.metrics import record_rollout_train_abs_diff, step_metric_key @@ -24,30 +22,61 @@ def prepare_critic_batch( ) -> PreparedBatch: """SFT flow matching on the student's x0 predictions, conditioned on their rollout prompts. - The last step's samples are scored at their noisy inputs, so its grid points come from the scoring range. + The last step's samples are scored at their noisy inputs, so its grid points come from the scoring range and + the teacher runs on them too. """ + scoring = _is_scoring_step(ctx, optim_step_idx) + prepared = prepare_sft_batch( + ctx, + _sft_batch(ctx, batch), + microbatch_id=microbatch_id, + optim_step_idx=optim_step_idx, + pad_to_len=pad_to_len, + grid_index_range=_score_grid_index_range(ctx) if scoring else None, + ) + return _request_teacher_forward(ctx, batch, prepared, pad_to_len=pad_to_len) if scoring else prepared + + +def _sft_batch(ctx: DiffusionLossContext, batch: list[dict]) -> list[dict]: config = ctx.train_pipeline_config - sft_batch = [ + return [ { "latent": {"visual": pair["x0"]}, "cond_kwargs": config.prepare_cond_kwargs(pair["denoising_env"].pos_cond_kwargs, ctx.device), } for pair in batch ] - grid_index_range = None - if _is_scoring_step(ctx, optim_step_idx): - min_sigma, max_sigma = ctx.args.dmd2_score_sigma_range - num_train_timesteps = config.num_train_timesteps - # Grid index i carries the unshifted sigma 1 - i / num_train_timesteps. - grid_index_range = (round(num_train_timesteps * (1 - max_sigma)), round(num_train_timesteps * (1 - min_sigma))) - return prepare_sft_batch( - ctx, - sft_batch, - microbatch_id=microbatch_id, - optim_step_idx=optim_step_idx, - pad_to_len=pad_to_len, - grid_index_range=grid_index_range, - ) + + +def _score_grid_index_range(ctx: DiffusionLossContext) -> tuple[int, int]: + min_sigma, max_sigma = ctx.args.dmd2_score_sigma_range + num_train_timesteps = ctx.train_pipeline_config.num_train_timesteps + # Grid index i carries the unshifted sigma 1 - i / num_train_timesteps. + return round(num_train_timesteps * (1 - max_sigma)), round(num_train_timesteps * (1 - min_sigma)) + + +def _request_teacher_forward( + ctx: DiffusionLossContext, batch: list[dict], prepared: PreparedBatch, *, pad_to_len: int | None +) -> PreparedBatch: + """Ask the trunk for the teacher at --dmd2-teacher-guidance-scale on this batch, with the rollout's negative + cond collated for its CFG when the scale needs one.""" + config = ctx.train_pipeline_config + guidance_scale = ctx.args.dmd2_teacher_guidance_scale + if guidance_scale <= 1.0: + return dataclasses.replace(prepared, teacher_guidance_scale=guidance_scale) + envs = [pair["denoising_env"] for pair in batch] + if any(env.neg_cond_kwargs is None for env in envs): + raise ValueError( + "--dmd2-teacher-guidance-scale > 1 needs the rollout's negative cond, " + "which the engine returns only for requests that run CFG" + ) + pos_list = [config.prepare_cond_kwargs(env.pos_cond_kwargs, ctx.device) for env in envs] + neg_list = [config.prepare_cond_kwargs(env.neg_cond_kwargs, ctx.device) for env in envs] + if config.cfg_batching: + joint_cond = config.collate_cond_for_sample_batch(pos_list + neg_list, ctx.device, pad_to_len=pad_to_len) + return dataclasses.replace(prepared, joint_cond=joint_cond, teacher_guidance_scale=guidance_scale) + neg_cond = config.collate_cond_for_sample_batch(neg_list, ctx.device, pad_to_len=pad_to_len) + return dataclasses.replace(prepared, neg_cond=neg_cond, teacher_guidance_scale=guidance_scale) def critic_loss_formula( @@ -58,6 +87,7 @@ def critic_loss_formula( new_pred: dict[str, torch.Tensor], old_pred: dict[str, torch.Tensor] | None, ref_pred: dict[str, torch.Tensor] | None, + teacher_pred: dict[str, torch.Tensor] | None = None, metrics: MetricBuffer, optim_step_idx: int, train_output_inputs: list, @@ -66,15 +96,15 @@ def critic_loss_formula( ) -> torch.Tensor: """The SFT loss in --dmd2-critic-loss-space. - On the last step it also keeps the critic's x0 at each noisy input, before that step's update. + On the last step it also keeps the critic's and the teacher's x0 at each noisy input, before that step's update. """ latents = prepared.latents["visual"] sigmas = prepared.extras["sigmas"]["visual"].view(len(batch), *([1] * (latents.ndim - 1))) if _is_scoring_step(ctx, optim_step_idx): x0_fake = latents - sigmas * new_pred["visual"].detach().float() - train_output_inputs.append( - (batch, prepared.component_name, latents, prepared.timesteps["visual"], sigmas, x0_fake) - ) + x0_real = latents - sigmas * teacher_pred["visual"].float() + for pair, real, fake in zip(batch, x0_real, x0_fake, strict=True): + train_output_inputs.append((pair["sample_index"], real, fake)) if ctx.args.dmd2_critic_loss_space == "x0": # x0 = x_sigma - sigma v, so the MSE on x0 weights the velocity MSE by sigma^2. x0_target = latents - sigmas * prepared.extras["target"]["visual"] @@ -98,79 +128,14 @@ def critic_loss_formula( def score_last_step_samples( ctx: DiffusionLossContext, train_pairs: list[dict], train_output_inputs: list ) -> dict[int, dict]: - """The teacher's x0 at each scored sample's noisy input, next to the critic's x0 kept there, by sample.""" - predictions = {} - for batch, component_name, latents, timesteps, sigmas, x0_fake in train_output_inputs: - teacher = ctx.teacher_models[component_name] - real_pred = _predict_velocity(ctx, teacher, batch, latents, timesteps, ctx.args.dmd2_teacher_guidance_scale) - for pair, x0_real, fake in zip(batch, latents - sigmas * real_pred, x0_fake, strict=True): - predictions[pair["sample_index"]] = {"x0_real": x0_real.cpu(), "x0_fake": fake.cpu()} - - # A no-grad forward leaves FSDP's root parameters gathered; sleep must move the shards. - for model in ctx.teacher_models.values(): - reshard_model(model) - return predictions + """The teacher's and the critic's x0 kept at each scored sample's noisy input, by sample.""" + return {index: {"x0_real": real.cpu(), "x0_fake": fake.cpu()} for index, real, fake in train_output_inputs} def _is_scoring_step(ctx: DiffusionLossContext, optim_step_idx: int) -> bool: return optim_step_idx == ctx.args.num_steps_per_rollout - 1 -def _predict_velocity( - ctx: DiffusionLossContext, - model: torch.nn.Module, - batch: list[dict], - latents: torch.Tensor, - timesteps: torch.Tensor, - guidance_scale: float, -) -> torch.Tensor: - """One velocity prediction, with CFG over the rollout's negative cond when ``guidance_scale > 1``.""" - config = ctx.train_pipeline_config - use_cfg = guidance_scale > 1.0 - envs = [pair["denoising_env"] for pair in batch] - if use_cfg and any(env.neg_cond_kwargs is None for env in envs): - raise ValueError( - "--dmd2-teacher-guidance-scale > 1 needs the rollout's negative cond, " - "which the engine returns only for requests that run CFG" - ) - pos_list = [config.prepare_cond_kwargs(env.pos_cond_kwargs, ctx.device) for env in envs] - neg_list = [config.prepare_cond_kwargs(env.neg_cond_kwargs, ctx.device) for env in envs] if use_cfg else [] - cfg_batching = use_cfg and config.cfg_batching - pos_cond = neg_cond = joint_cond = None - if cfg_batching: - joint_cond = config.collate_cond_for_sample_batch(pos_list + neg_list, ctx.device) - else: - pos_cond = config.collate_cond_for_sample_batch(pos_list, ctx.device) - if use_cfg: - neg_cond = config.collate_cond_for_sample_batch(neg_list, ctx.device) - - latents_in, timesteps_in, (pos_in, neg_in, joint_in) = apply_input_dtype_policy( - config.input_dtype_policy, - latents={"visual": latents}, - timesteps={"visual": config.process_timestep_as_input(timesteps)}, - conds=(pos_cond, neg_cond, joint_cond), - default_dtype=ctx.forward_dtype, - ) - with torch.autocast( - "cuda", - dtype=ctx.forward_dtype, - enabled=ctx.forward_dtype != torch.float32 and config.enable_autocast, - ): - pred = config.compute_noise_pred( - model=model, - latents_input=latents_in, - timesteps_input=timesteps_in, - pos_cond=pos_in, - neg_cond=neg_in, - joint_cond=joint_in, - use_cfg=use_cfg, - cfg_batching=cfg_batching, - guidance_scale=guidance_scale, - true_cfg_scale=None, - ) - return pred["visual"].float() - - def select_scored_pairs(ctx: DiffusionLossContext, train_pairs: list[dict]) -> list[dict]: """The pairs of the critic's last step, which it scored; the actor trains on these only.""" scores = ctx.external_data["critic"] @@ -231,6 +196,7 @@ def dmd2_loss_formula( new_pred: dict[str, torch.Tensor], old_pred: dict[str, torch.Tensor] | None, ref_pred: dict[str, torch.Tensor] | None, + teacher_pred: dict[str, torch.Tensor] | None = None, metrics: MetricBuffer, optim_step_idx: int, train_output_inputs: list, diff --git a/miles/backends/fsdp_utils/loss_hub/flow_grpo.py b/miles/backends/fsdp_utils/loss_hub/flow_grpo.py index 48eab4052..acb203b7f 100644 --- a/miles/backends/fsdp_utils/loss_hub/flow_grpo.py +++ b/miles/backends/fsdp_utils/loss_hub/flow_grpo.py @@ -120,6 +120,7 @@ def flow_grpo_loss_formula( new_pred: dict[str, torch.Tensor], old_pred: dict[str, torch.Tensor] | None, ref_pred: dict[str, torch.Tensor] | None, + teacher_pred: dict[str, torch.Tensor] | None = None, metrics: MetricBuffer, optim_step_idx: int, train_output_inputs: list, diff --git a/miles/backends/fsdp_utils/loss_hub/nft.py b/miles/backends/fsdp_utils/loss_hub/nft.py index 88765cd94..f5ed466b1 100644 --- a/miles/backends/fsdp_utils/loss_hub/nft.py +++ b/miles/backends/fsdp_utils/loss_hub/nft.py @@ -113,6 +113,7 @@ def nft_loss_formula( new_pred: dict[str, torch.Tensor], old_pred: dict[str, torch.Tensor] | None, ref_pred: dict[str, torch.Tensor] | None, + teacher_pred: dict[str, torch.Tensor] | None = None, metrics: MetricBuffer, optim_step_idx: int, train_output_inputs: list, diff --git a/miles/backends/fsdp_utils/loss_hub/sft.py b/miles/backends/fsdp_utils/loss_hub/sft.py index df1ca25a3..9fb0a5552 100644 --- a/miles/backends/fsdp_utils/loss_hub/sft.py +++ b/miles/backends/fsdp_utils/loss_hub/sft.py @@ -127,6 +127,7 @@ def sft_loss_formula( new_pred: dict[str, torch.Tensor], old_pred: dict[str, torch.Tensor] | None, ref_pred: dict[str, torch.Tensor] | None, + teacher_pred: dict[str, torch.Tensor] | None = None, metrics: MetricBuffer, optim_step_idx: int, train_output_inputs: list, diff --git a/miles/backends/fsdp_utils/loss_hub/types.py b/miles/backends/fsdp_utils/loss_hub/types.py index 129d08cad..449d49a34 100644 --- a/miles/backends/fsdp_utils/loss_hub/types.py +++ b/miles/backends/fsdp_utils/loss_hub/types.py @@ -26,7 +26,6 @@ class DiffusionLossContext: rollout_id: int = 0 dp_rank: int = 0 reference_models: dict[str, torch.nn.Module] = field(default_factory=dict) - teacher_models: dict[str, torch.nn.Module] = field(default_factory=dict) external_data: dict[str, Any] = field(default_factory=dict) @@ -70,3 +69,5 @@ class PreparedBatch: joint_cond: dict | None advantage: torch.Tensor extras: dict[str, Any] = field(default_factory=dict) + # CFG scale of the frozen teacher's no-grad forward on this batch; None runs no teacher forward. + teacher_guidance_scale: float | None = None diff --git a/tests/fast/backends/fsdp_utils/test_loss_hub_dmd2.py b/tests/fast/backends/fsdp_utils/test_loss_hub_dmd2.py index c05447b30..aa3a08501 100644 --- a/tests/fast/backends/fsdp_utils/test_loss_hub_dmd2.py +++ b/tests/fast/backends/fsdp_utils/test_loss_hub_dmd2.py @@ -6,15 +6,17 @@ (the critic's K steps are the SFT loss on the student's samples; the last step, whose samples get scored, draws grid points whose unshifted sigma lies in --dmd2-score-sigma-range, default [0.02, 0.98]) + │ + the last step also asks the trunk for the teacher, PreparedBatch.teacher_guidance_scale, + with the rollout's neg cond collated for its CFG) + │ + the trunk runs the teacher without grad at x_s before the critic's training forward ──► v_real │ critic_loss_formula ──► sft_loss_formula on v, or on x0 = x_s - sigma v under --dmd2-critic-loss-space x0; - on the last step it also keeps, per micro-batch, - x_s = that step's noisy input, sigma, and x0_fake = x_s - sigma v_fake from the - training forward, i.e. the critic before the last update + on the last step it also keeps, per sample, x0_fake = x_s - sigma v_fake from the + training forward, i.e. the critic before the last update, and x0_real = x_s - sigma v_real │ - score_last_step_samples, without grad after the critic's steps, per kept micro-batch: - teacher, CFG --dmd2-teacher-guidance-scale over the rollout's neg cond ──► x0_real = x_s - sigma v_real - ──► {sample_index: {"x0_real", "x0_fake"}}; the teacher is resharded so sleep moves its shards + score_last_step_samples, after the critic's steps ──► {sample_index: {"x0_real", "x0_fake"}} on the host │ ctx.external_data["critic"] on the paired actor rank select_scored_pairs ──► the actor's train-input hook keeps only the scored pairs, i.e. the critic's last step prepare_generator_batch ──► the student's unguided step i on the rollout input x_i @@ -30,10 +32,12 @@ test_critic_loss_is_the_sft_loss loss and metrics == sft_loss_formula on every step test_x0_critic_loss_weights_the_velocity_mse x0 loss == x0 MSE == sigma^2 * velocity MSE, input intact test_only_the_last_step_keeps_scoring_inputs earlier steps keep nothing, so only the last step is scored - test_scores_match_separate_forwards_at_the_kept_input fused scores == critic and teacher forwards run apart at x_s - test_teacher_runs_cfg_and_the_critic_runs_unguided CFG combine for the teacher only - test_teacher_cfg_needs_the_rollout_negative_cond rejected instead of a forward without text - test_scoring_reshards_the_teacher teacher resharded after its no-grad forwards + test_earlier_steps_ask_for_no_teacher no teacher scale, no negative cond before the last step + test_last_step_asks_for_the_guided_teacher teacher scale and the neg cond collated per CFG batching + test_unguided_teacher_needs_no_negative_cond scale 1: the teacher reads only the positive cond + test_teacher_cfg_needs_the_rollout_negative_cond rejected at prepare instead of a forward without text + test_scores_are_x0_at_the_kept_input x0_fake and x0_real == x_s - sigma v of each forward + test_teacher_runs_cfg_and_the_critic_runs_unguided CFG combine for the teacher only; kept x0 carry no grad test_actor_keeps_the_critic_last_step_pairs same shard ──► the actor trains on the scored 1/K only test_scores_outside_the_shard_are_rejected a broken rank pairing fails instead of shrinking the batch test_generator_batch_is_the_student_step_on_its_input x_i, t_i, sigma_i and the positive cond, no CFG @@ -73,7 +77,7 @@ class _CondVelocity(nn.Module): def __init__(self, scale): super().__init__() - self.scale = scale + self.scale = nn.Parameter(torch.tensor(float(scale))) def forward(self, hidden_states, timestep, return_dict, encoder_hidden_states, pooled_projections): text = encoder_hidden_states.mean(dim=(1, 2)).view(-1, 1, 1, 1) @@ -113,10 +117,9 @@ def _pairs(num_pairs, with_neg=True): ] -def _ctx(teacher_guidance_scale=3.0, critic_scale=1.0, teacher_scale=1.0): +def _ctx(teacher_guidance_scale=3.0, critic_scale=1.0): return DiffusionLossContext( models={"transformer": _CondVelocity(critic_scale)}, - teacher_models={"transformer": _CondVelocity(teacher_scale)}, train_pipeline_config=SD3TrainPipelineConfig(), sde_backend=None, args=Namespace( @@ -137,25 +140,51 @@ def _ctx(teacher_guidance_scale=3.0, critic_scale=1.0, teacher_scale=1.0): ) -def _critic_step(ctx, pairs, optim_step_idx, train_output_inputs, metrics=None): - """One critic optimizer step as _train_core runs it: prepare, the critic's training forward, the loss hook.""" +def _forward(config, model, prepared, *, use_cfg, cfg_batching, guidance_scale): + return config.compute_noise_pred( + model=model, + latents_input=prepared.latents, + timesteps_input=prepared.timesteps_for_model, + pos_cond=prepared.pos_cond, + neg_cond=prepared.neg_cond, + joint_cond=prepared.joint_cond, + use_cfg=use_cfg, + cfg_batching=cfg_batching, + guidance_scale=guidance_scale, + true_cfg_scale=None, + ) + + +def _critic_step(ctx, pairs, optim_step_idx, train_output_inputs, metrics=None, teacher=None): + """One critic optimizer step as _train_core runs it: prepare, the teacher forward it asks for, the critic's + training forward, the loss hook.""" + config = ctx.train_pipeline_config + teacher = _CondVelocity(1.0) if teacher is None else teacher steps = [] for start in range(0, len(pairs), ctx.args.micro_batch_size): batch = pairs[start : start + ctx.args.micro_batch_size] prepared = dmd2.prepare_critic_batch( ctx, batch, microbatch_id=optim_step_idx * 10 + start, optim_step_idx=optim_step_idx ) - new_pred = ctx.train_pipeline_config.compute_noise_pred( - model=prepared.model, - latents_input=prepared.latents, - timesteps_input=prepared.timesteps_for_model, - pos_cond=prepared.pos_cond, - neg_cond=None, - joint_cond=None, + teacher_pred = None + if prepared.teacher_guidance_scale is not None: + use_cfg = prepared.teacher_guidance_scale > 1.0 + with torch.no_grad(): + teacher_pred = _forward( + config, + teacher, + prepared, + use_cfg=use_cfg, + cfg_batching=use_cfg and config.cfg_batching, + guidance_scale=prepared.teacher_guidance_scale, + ) + new_pred = _forward( + config, + prepared.model, + prepared, use_cfg=prepared.use_cfg, cfg_batching=prepared.cfg_batching, guidance_scale=prepared.guidance_scale, - true_cfg_scale=None, ) loss = dmd2.critic_loss_formula( ctx, @@ -164,6 +193,7 @@ def _critic_step(ctx, pairs, optim_step_idx, train_output_inputs, metrics=None): new_pred=new_pred, old_pred=None, ref_pred=None, + teacher_pred=teacher_pred, metrics=metrics or _Metrics(), optim_step_idx=optim_step_idx, train_output_inputs=train_output_inputs, @@ -283,39 +313,88 @@ def test_only_the_last_step_keeps_scoring_inputs(): assert inputs == [] _critic_step(ctx, pairs[6:], CRITIC_STEPS - 1, inputs) - assert len(inputs) == 2 # one entry per micro-batch of the last step + assert [index for index, _, _ in inputs] == [106, 107, 108] scores = dmd2.score_last_step_samples(ctx, pairs, inputs) assert list(scores) == [106, 107, 108] -def test_scores_match_separate_forwards_at_the_kept_input(): +def test_earlier_steps_ask_for_no_teacher(): + ctx = _ctx(teacher_guidance_scale=3.0) + for optim_step_idx in range(CRITIC_STEPS - 1): + prepared = dmd2.prepare_critic_batch(ctx, _pairs(2), microbatch_id=0, optim_step_idx=optim_step_idx) + assert prepared.teacher_guidance_scale is None + assert prepared.neg_cond is None and prepared.joint_cond is None + + +@pytest.mark.parametrize("cfg_batching", [False, True]) +def test_last_step_asks_for_the_guided_teacher(cfg_batching): + ctx = _ctx(teacher_guidance_scale=3.0) + config = ctx.train_pipeline_config + config.cfg_batching = cfg_batching + pairs = _pairs(2) + + prepared = dmd2.prepare_critic_batch(ctx, pairs, microbatch_id=0, optim_step_idx=CRITIC_STEPS - 1) + + assert prepared.teacher_guidance_scale == 3.0 + assert not prepared.use_cfg and not prepared.cfg_batching + pos_list = [config.prepare_cond_kwargs(pair["denoising_env"].pos_cond_kwargs, ctx.device) for pair in pairs] + neg_list = [config.prepare_cond_kwargs(pair["denoising_env"].neg_cond_kwargs, ctx.device) for pair in pairs] + pos = config.collate_cond_for_sample_batch(pos_list, ctx.device)["encoder_hidden_states"] + assert torch.equal(prepared.pos_cond["encoder_hidden_states"], pos) + if cfg_batching: + joint = config.collate_cond_for_sample_batch(pos_list + neg_list, ctx.device)["encoder_hidden_states"] + assert prepared.neg_cond is None + assert torch.equal(prepared.joint_cond["encoder_hidden_states"], joint) + else: + neg = config.collate_cond_for_sample_batch(neg_list, ctx.device)["encoder_hidden_states"] + assert prepared.joint_cond is None + assert torch.equal(prepared.neg_cond["encoder_hidden_states"], neg) + + +def test_unguided_teacher_needs_no_negative_cond(): + ctx = _ctx(teacher_guidance_scale=1.0) + prepared = dmd2.prepare_critic_batch( + ctx, _pairs(2, with_neg=False), microbatch_id=0, optim_step_idx=CRITIC_STEPS - 1 + ) + assert prepared.teacher_guidance_scale == 1.0 + assert prepared.neg_cond is None and prepared.joint_cond is None + + +def test_teacher_cfg_needs_the_rollout_negative_cond(): ctx = _ctx(teacher_guidance_scale=3.0) + with pytest.raises(ValueError, match="needs the rollout's negative cond"): + dmd2.prepare_critic_batch(ctx, _pairs(2, with_neg=False), microbatch_id=0, optim_step_idx=CRITIC_STEPS - 1) + # Earlier steps run no teacher, so they take pairs without a negative cond. + dmd2.prepare_critic_batch(ctx, _pairs(2, with_neg=False), microbatch_id=0, optim_step_idx=0) + + +def test_scores_are_x0_at_the_kept_input(): + ctx = _ctx(teacher_guidance_scale=1.0) ctx.models["transformer"] = _NoisyInputVelocity() pairs = _pairs(5) inputs = [] - steps = _critic_step(ctx, pairs, CRITIC_STEPS - 1, inputs) + steps = _critic_step(ctx, pairs, CRITIC_STEPS - 1, inputs, teacher=_NoisyInputVelocity()) scores = dmd2.score_last_step_samples(ctx, pairs, inputs) assert list(scores) == [100, 101, 102, 103, 104] for batch, prepared, _, _ in steps: x_s = prepared.latents["visual"] - timesteps = prepared.timesteps["visual"] + velocity = x_s + prepared.timesteps_for_model["visual"].view(-1, 1, 1, 1) sigma = prepared.extras["sigmas"]["visual"].view(-1, 1, 1, 1) - fake = dmd2._predict_velocity(ctx, ctx.models["transformer"], batch, x_s, timesteps, 1.0) - real = dmd2._predict_velocity(ctx, ctx.teacher_models["transformer"], batch, x_s, timesteps, 3.0) for n, pair in enumerate(batch): - assert torch.equal(scores[pair["sample_index"]]["x0_fake"], x_s[n] - sigma[n] * fake[n]) - assert torch.equal(scores[pair["sample_index"]]["x0_real"], x_s[n] - sigma[n] * real[n]) + assert torch.equal(scores[pair["sample_index"]]["x0_fake"], x_s[n] - sigma[n] * velocity[n]) + assert torch.equal(scores[pair["sample_index"]]["x0_real"], x_s[n] - sigma[n] * velocity[n]) def test_teacher_runs_cfg_and_the_critic_runs_unguided(): - ctx = _ctx(teacher_guidance_scale=3.0, teacher_scale=1.0, critic_scale=2.0) + ctx = _ctx(teacher_guidance_scale=3.0, critic_scale=2.0) + teacher = _CondVelocity(1.0) pairs = _pairs(2) inputs = [] - [(_, prepared, _, _)] = _critic_step(ctx, pairs, CRITIC_STEPS - 1, inputs) + [(_, prepared, _, loss)] = _critic_step(ctx, pairs, CRITIC_STEPS - 1, inputs, teacher=teacher) scores = dmd2.score_last_step_samples(ctx, pairs, inputs) x_s = prepared.latents["visual"] @@ -326,31 +405,11 @@ def test_teacher_runs_cfg_and_the_critic_runs_unguided(): scores[pair["sample_index"]]["x0_real"], x_s[n] - sigma[n] * (neg + 3.0 * (pos - neg)) ) torch.testing.assert_close(scores[pair["sample_index"]]["x0_fake"], x_s[n] - sigma[n] * 2.0 * pos) - - -def test_teacher_cfg_needs_the_rollout_negative_cond(): - ctx = _ctx(teacher_guidance_scale=3.0) - inputs = [] - _critic_step(ctx, _pairs(2, with_neg=False), CRITIC_STEPS - 1, inputs) - with pytest.raises(ValueError, match="needs the rollout's negative cond"): - dmd2.score_last_step_samples(ctx, _pairs(2, with_neg=False), inputs) - # Unguided, the teacher reads only the positive cond. - ctx = _ctx(teacher_guidance_scale=1.0) - inputs = [] - _critic_step(ctx, _pairs(2, with_neg=False), CRITIC_STEPS - 1, inputs) - dmd2.score_last_step_samples(ctx, _pairs(2, with_neg=False), inputs) - - -def test_scoring_reshards_the_teacher(monkeypatch): - resharded = [] - monkeypatch.setattr(dmd2, "reshard_model", resharded.append) - ctx = _ctx() - inputs = [] - _critic_step(ctx, _pairs(2), CRITIC_STEPS - 1, inputs) - - dmd2.score_last_step_samples(ctx, _pairs(2), inputs) - - assert resharded == [ctx.teacher_models["transformer"]] + assert not scores[pair["sample_index"]]["x0_real"].requires_grad + assert not scores[pair["sample_index"]]["x0_fake"].requires_grad + loss.backward() + assert ctx.models["transformer"].scale.grad is not None + assert teacher.scale.grad is None def test_actor_keeps_the_critic_last_step_pairs(): diff --git a/tests/fast/backends/fsdp_utils/test_reference_models.py b/tests/fast/backends/fsdp_utils/test_reference_models.py index f57aaadfb..e90e271a2 100644 --- a/tests/fast/backends/fsdp_utils/test_reference_models.py +++ b/tests/fast/backends/fsdp_utils/test_reference_models.py @@ -2,7 +2,7 @@ full / new / saved LoRA -> actor (trainable) ---> loss ---> gradients + optimizer step +-> reference (full or LoRA) --no_grad--/ - +-> teacher (LoRA) -----------no_grad--/ + +-> teacher (LoRA) -----------no_grad--/ runs first, when prepare asks for it two components ---> select the matching role component LoRA base reference ---> disable adapter ---> adapters and their gradients back on the actor FSDP2 kept-gathered ---> lora_base forward ---> next step still trains the adapters @@ -84,11 +84,16 @@ def fsdp_parallel_plan(self, model): class TinyPipelineConfig: input_dtype_policy = {} + cfg_batching = False + + def __init__(self): + self.noise_pred_calls = [] def postprocess_model_after_materialize(self, model): pass def compute_noise_pred(self, *, model, latents_input, **kwargs): + self.noise_pred_calls.append((model, kwargs)) return {"visual": model(latents_input["visual"])} @@ -122,7 +127,7 @@ def save_component_lora_adapters(path): return adapter_paths -def load_actor_forward_method(): +def load_actor_forward_method(reshard_model=reshard_model): path = Path(__file__).resolve().parents[4] / "miles/backends/fsdp_utils/actor.py" source = ast.parse(path.read_text()) actor = next(node for node in source.body if isinstance(node, ast.ClassDef) and node.name == "FSDPTrainRayActor") @@ -141,7 +146,17 @@ def load_actor_forward_method(): def make_actor_forward_harness( - models, reference_models, component, inputs, ref_mode, *, loss_type="policy_loss", ema_optimizer=None + models, + reference_models, + component, + inputs, + ref_mode, + *, + loss_type="policy_loss", + ema_optimizer=None, + teacher_models=None, + teacher_guidance_scale=None, + true_cfg_scale=None, ): observed = {} prepared = SimpleNamespace( @@ -155,18 +170,20 @@ def make_actor_forward_harness( use_cfg=False, cfg_batching=False, guidance_scale=1.0, - true_cfg_scale=None, + true_cfg_scale=true_cfg_scale, + teacher_guidance_scale=teacher_guidance_scale, ) def prepare(ctx, batch, **kwargs): observed["prepare_kwargs"] = kwargs return prepared - def loss_formula(ctx, batch, prepared, *, new_pred, old_pred, ref_pred, **kwargs): - predictions = {"new_pred": new_pred, "old_pred": old_pred, "ref_pred": ref_pred} + def loss_formula(ctx, batch, prepared, *, new_pred, old_pred, ref_pred, teacher_pred, **kwargs): + predictions = {"new_pred": new_pred, "old_pred": old_pred, "ref_pred": ref_pred, "teacher_pred": teacher_pred} observed.update({name: pred["visual"] for name, pred in predictions.items() if pred is not None}) observed["formula_kwargs"] = kwargs - return (new_pred["visual"] - ref_pred["visual"]).square().mean() + target = torch.zeros_like(new_pred["visual"]) if ref_pred is None else ref_pred["visual"] + return (new_pred["visual"] - target).square().mean() harness = SimpleNamespace( args=Namespace(ref_mode=ref_mode, loss_type=loss_type), @@ -174,6 +191,7 @@ def loss_formula(ctx, batch, prepared, *, new_pred, old_pred, ref_pred, **kwargs ema_optimizer=ema_optimizer, model=torch.nn.ModuleDict(models), reference_models=reference_models, + teacher_models={} if teacher_models is None else teacher_models, train_pipeline_config=TinyPipelineConfig(), _forward_dtype=torch.float32, loss_hooks=SimpleNamespace(prepare=prepare, formula=loss_formula), @@ -511,3 +529,85 @@ def test_the_trunk_hands_the_hooks_their_own_counters_and_the_one_list(): assert observed["prepare_kwargs"] == {"microbatch_id": 7, "optim_step_idx": 2, "pad_to_len": None} assert observed["formula_kwargs"]["optim_step_idx"] == 2 assert observed["formula_kwargs"]["train_output_inputs"] is train_output_inputs + + +def _teacher_harness(teacher_guidance_scale, *, with_teacher=True, true_cfg_scale=None): + actor, teacher = TinyComponent(), TinyComponent() + order = [] + actor.register_forward_hook(lambda *_: order.append("actor")) + teacher.register_forward_hook(lambda *_: order.append("teacher")) + harness, observed = make_actor_forward_harness( + {"transformer": actor}, + {}, + "transformer", + torch.ones(2, 3), + "none", + teacher_models={"transformer": teacher} if with_teacher else None, + teacher_guidance_scale=teacher_guidance_scale, + true_cfg_scale=true_cfg_scale, + ) + observed["order"] = order + return harness, observed, actor, teacher + + +def _run_forward(harness, reshard_model=reshard_model): + return load_actor_forward_method(reshard_model=reshard_model)( + harness, None, [], microbatch_id=0, optim_step_idx=0, train_output_inputs=[], metrics=None + ) + + +@pytest.mark.parametrize("cfg_batching", [False, True]) +def test_the_teacher_runs_first_without_grad_with_its_own_cfg(cfg_batching): + # true_cfg_scale overrides guidance_scale in cfg_combine, so the student's must not reach the teacher. + harness, observed, actor, teacher = _teacher_harness(3.0, true_cfg_scale=7.0) + harness.train_pipeline_config.cfg_batching = cfg_batching + resharded = [] + + _run_forward(harness, reshard_model=resharded.append).backward() + + assert observed["order"] == ["teacher", "actor"] + assert resharded == [teacher] + assert not observed["teacher_pred"].requires_grad + with torch.no_grad(): + torch.testing.assert_close(observed["teacher_pred"], teacher(torch.ones(2, 3))) + assert actor.block.proj.weight.grad is not None and teacher.block.proj.weight.grad is None + [(teacher_model, teacher_call), (actor_model, actor_call)] = harness.train_pipeline_config.noise_pred_calls + assert teacher_model is teacher and actor_model is actor + assert (teacher_call["use_cfg"], teacher_call["cfg_batching"], teacher_call["guidance_scale"]) == ( + True, + cfg_batching, + 3.0, + ) + assert teacher_call["true_cfg_scale"] is None + assert (actor_call["use_cfg"], actor_call["cfg_batching"], actor_call["guidance_scale"]) == (False, False, 1.0) + assert actor_call["true_cfg_scale"] == 7.0 + + +def test_an_unguided_teacher_runs_without_cfg(): + harness, _, _, teacher = _teacher_harness(1.0) + harness.train_pipeline_config.cfg_batching = True + + _run_forward(harness, reshard_model=lambda model: None) + + [(teacher_model, teacher_call), _] = harness.train_pipeline_config.noise_pred_calls + assert teacher_model is teacher + assert (teacher_call["use_cfg"], teacher_call["cfg_batching"], teacher_call["guidance_scale"]) == ( + False, + False, + 1.0, + ) + + +def test_no_teacher_forward_unless_the_prepare_hook_asks(): + harness, observed, _, teacher = _teacher_harness(None) + + _run_forward(harness) + + assert teacher.forward_count.item() == 0 and "teacher_pred" not in observed + assert observed["order"] == ["actor"] + + +def test_a_teacher_request_without_a_teacher_is_rejected(): + harness, _, _, _ = _teacher_harness(3.0, with_teacher=False) + with pytest.raises(ValueError, match="--teacher-load"): + _run_forward(harness) diff --git a/tests/fast/backends/fsdp_utils/test_train_input_hook.py b/tests/fast/backends/fsdp_utils/test_train_input_hook.py index ccb573cc9..b01bf3384 100644 --- a/tests/fast/backends/fsdp_utils/test_train_input_hook.py +++ b/tests/fast/backends/fsdp_utils/test_train_input_hook.py @@ -60,7 +60,6 @@ def _actor(train_input, train_output, forwarded, **args): lists=lists, models={}, reference_models={}, - teacher_models={}, train_pipeline_config=None, sde_backend=None, args=Namespace( diff --git a/tests/fast/utils/test_reference_arguments.py b/tests/fast/utils/test_reference_arguments.py index 890b55844..33231e017 100644 --- a/tests/fast/utils/test_reference_arguments.py +++ b/tests/fast/utils/test_reference_arguments.py @@ -2,7 +2,7 @@ actor: full / LoRA ---> ref: base / base + LoRA, teacher: base / base + LoRA actor: LoRA ---> lora_base: reuse actor with its adapter disabled - teacher ---> loaded for whichever hook reads ctx.teacher_models; nothing in args says who will + teacher ---> run by the trunk when a prepare hook asks for it; nothing in args says which will actor LoRA enabled --> adapter config --> checkpoint A/B support + uniform IPC scaling + CLI r/alpha match adapter paths ---> one plain PEFT directory per component, in order; any other count is rejected