diff --git a/docs/advanced/dtype-control.md b/docs/advanced/dtype-control.md index 3b9411582..36b30e72c 100644 --- a/docs/advanced/dtype-control.md +++ b/docs/advanced/dtype-control.md @@ -56,9 +56,11 @@ input_dtype_policy = {"latents": "default", "cond": "default", "timestep": None} input_dtype_policy = {"latents": "default", "cond": None, "timestep": "fp32"} ``` -**Division of labour:** `input_dtype_policy` owns the boundary; autocast owns the interior. That -split also keeps gradient-checkpointing recompute consistent, since the recomputed forward sees -the same ambient autocast as the original. Autocast is off when `--diffusion-forward-dtype` is +**Division of labour:** `input_dtype_policy` owns the boundary; autocast owns the interior. The +trainer resolves the policy once per run and casts each stage's inputs with it as it sends them to the +model, the teacher's and the actor's extra forward included; the prepared batch itself keeps the rollout +dtypes for the loss. That split also keeps gradient-checkpointing recompute consistent, since the +recomputed forward sees the same ambient autocast as the original. Autocast is off when `--diffusion-forward-dtype` is `fp32` and for families that set `enable_autocast = False` (MiniMax H3). ## 3. Per-parameter dtype overrides diff --git a/docs/fsdp_model_roles.md b/docs/fsdp_model_roles.md index af33d85cf..e79a5a2fe 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 returns a `PreparedBatches.teacher` stage, 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/models/h3/h3.md b/docs/models/h3/h3.md index fb63a8783..0bdb0f0fe 100644 --- a/docs/models/h3/h3.md +++ b/docs/models/h3/h3.md @@ -81,6 +81,19 @@ MILES_SCRIPT_EXTERNAL_RAY=1 python3 scripts/run_diffusion_dmd2_h3_t2va_16gpu_mul MILES_SCRIPT_EXTERNAL_RAY=1 python3 scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py --reference fasth3 ``` +The same script runs on one node for smoke runs; `tests/e2e/short/test_h3_t2va_dmd2_16xGPU_single_node_2xGPU_proxy.py` runs +this 2-GPU proxy in CI (2 rollouts of 4 prompts, 2 critic steps, no eval or checkpoints). Below +16 GPUs the two 31B optimizers do not fit next to the models, so `--fsdp-cpu-offload` keeps +parameters, gradients and optimizer states in host memory (about 1.1 TB; the optimizer steps on the +CPU). The master stays fp32: H3 pins proj_in / time_embedder / proj_out to fp32, and FSDP2 wants one +original dtype across a group's trainable parameters. + +```bash +python3 scripts/run_diffusion_dmd2_h3_t2va_16gpu_multinode.py --num-nodes 1 --num-gpus-per-node 2 \ + --rollout-batch-size 4 --critic-steps-per-rollout 2 --num-rollout 2 --eval-interval 0 \ + --save-interval 0 --fsdp-cpu-offload +``` + What to watch: | Signal | Where | Reading | diff --git a/docs/user-guide/cli-reference.md b/docs/user-guide/cli-reference.md index e84db4693..2aa0c851a 100644 --- a/docs/user-guide/cli-reference.md +++ b/docs/user-guide/cli-reference.md @@ -278,7 +278,7 @@ See [Dtype Control](../advanced/dtype-control.md). | `--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 returns a `PreparedBatches.teacher` stage, 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. | @@ -293,6 +293,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 532a7ba4b..8fc081936 100644 --- a/docs/user-guide/customization.md +++ b/docs/user-guide/customization.md @@ -272,6 +272,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 its prepare hook also returns the +scoring batch, at its own draw, as the teacher's stage and as the critic's actor-forward stage +(`PreparedBatches.teacher` / `.actor_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. @@ -299,26 +302,34 @@ def convert_samples_to_train_data(args, samples) -> dict: ### `--custom-prepare-train-batch-path` ```python -def prepare(ctx, batch, *, microbatch_id, optim_step_idx, pad_to_len=None) -> PreparedBatch: +def prepare(ctx, batch, *, microbatch_id, optim_step_idx, pad_to_len=None) -> PreparedBatches: ... ``` Read only under `--loss-type custom_loss`; the other loss types take their prepare from the loss hub's table -above. Builds DiT inputs from train pairs. `microbatch_id` numbers the micro-batch within the rollout (training +above. Builds the micro-batch's stages from train pairs: `PreparedBatches(actor=...)` for the training forward alone, +plus `teacher=` and `actor_forward=` when the loss wants those forwards too. `microbatch_id` numbers the micro-batch within the rollout (training counts from 0; the old-log-prob recompute of windows 1.. passes their training forwards' numbers) and `optim_step_idx` is its optimizer step; the built-in hooks seed their noise from `microbatch_id`. -`PreparedBatch.latents`, `timesteps` and -`timesteps_for_model` are keyed by latent stream name: `"visual"`, plus e.g. -`"audio"` for joint audio-video models. `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`. +Each stage is a `PreparedBatch`; its `latents`, `timesteps` and `timesteps_for_model` are keyed by latent stream +name: `"visual"`, plus e.g. `"audio"` for joint audio-video models. + +| stage | model | grad | the formula receives | +|---|---|---|---| +| `actor` | the actor (the EMA and reference forwards take this batch too) | yes | `prepared` (positional), `new_pred`, `old_pred`, `ref_pred` | +| `teacher` | the frozen teacher of `--teacher-load`, by `component_name`; its own CFG fields and `neg_cond` / `joint_cond` | no | `teacher_batch`, `teacher_pred` | +| `actor_forward` | the actor's model, a second no-grad forward | no | `actor_forward_batch`, `actor_forward_pred` | + +The teacher and actor-forward stages run before the training forward. As the actor sends a stage to its model it +casts that batch's latents, `timesteps_for_model` and conds to the family's boundary dtypes (`input_dtype_policy`, +resolved once per run); the batch's own fields stay as rollout handed them, which is what the formulas read. ### `--custom-loss-function-path` ```python def loss_formula( - ctx, batch, prepared, *, new_pred, old_pred, ref_pred, teacher_pred, metrics, optim_step_idx, - train_output_inputs, **kwargs + ctx, batch, prepared, *, new_pred, old_pred, ref_pred, teacher_pred, teacher_batch, actor_forward_pred, + actor_forward_batch, metrics, optim_step_idx, train_output_inputs, **kwargs ): ... ``` @@ -328,8 +339,9 @@ 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 `teacher_batch`, the stage the prepare hook returned as `PreparedBatches.teacher`, run before +the training forward; `actor_forward_pred` is the actor's no-grad prediction on `actor_forward_batch` +(`PreparedBatches.actor_forward`). A stage the hook did not return arrives as `None` for both its pred and its batch. ### `--custom-train-input-postprocess-path` diff --git a/miles/backends/fsdp_utils/actor.py b/miles/backends/fsdp_utils/actor.py index 3ad8db1e2..ef554438d 100644 --- a/miles/backends/fsdp_utils/actor.py +++ b/miles/backends/fsdp_utils/actor.py @@ -39,8 +39,8 @@ DiffusionUpdateWeightLoRADistributed, ) from .ema import EMAOptimizer, reshard_model -from .input_dtype_policy import apply_input_dtype_policy -from .loss_hub import DiffusionLossContext, get_loss_hooks +from .input_dtype_policy import InputDtypes +from .loss_hub import DiffusionLossContext, PreparedBatches, get_loss_hooks from .lr_scheduler import get_lr_scheduler from .metrics import new_metric_buffer from .mixed_precision import parse_dtype_from_str @@ -108,6 +108,8 @@ def init(self, args: Namespace, role: str, with_ref: bool = False) -> int: # ty self.train_pipeline_config = load_function(args.train_pipeline_config_path)() self.train_pipeline_config.configure(args) + # The family's boundary dtypes, resolved once; every stage's inputs are cast with them as they are sent. + self._input_dtypes = InputDtypes.resolve(self.train_pipeline_config.input_dtype_policy, self._forward_dtype) self.model_backend = load_function(args.model_backend_path)(self.train_pipeline_config) if args.deterministic_mode: # flash-attn is opaque to torch's determinism flag; backends patch their own dispatch. @@ -525,29 +527,21 @@ def _forward_train_pair_batch( ) -> 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( + prepared_batches = self.loss_hooks.prepare( ctx, batch, microbatch_id=microbatch_id, optim_step_idx=optim_step_idx, pad_to_len=pad_to_len ) + if not isinstance(prepared_batches, PreparedBatches): + raise TypeError( + f"the prepare hook (--custom-prepare-train-batch-path) must return PreparedBatches, " + f"got {type(prepared_batches).__name__}" + ) train_pipeline_config = self.train_pipeline_config forward_dtype = self._forward_dtype + prepared = prepared_batches.actor - # 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( - train_pipeline_config.input_dtype_policy, - latents=prepared.latents, - timesteps=prepared.timesteps_for_model, - conds=(prepared.pos_cond, prepared.neg_cond, prepared.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]: + def _compute_noise_pred(model, batch_in) -> dict[str, torch.Tensor]: + # The batch's inputs are cast to the family's boundary dtypes as they are sent; op interiors stay + # autocast-managed. with torch.autocast( "cuda", dtype=forward_dtype, @@ -555,51 +549,47 @@ def _compute_noise_pred( ): 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, + **batch_in.model_inputs(self._input_dtypes), + 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 + teacher_batch = prepared_batches.teacher + if teacher_batch is not None: + if teacher_batch.component_name not in self.teacher_models: + raise ValueError("the prepared batches ask for a teacher forward, which needs --teacher-load") + teacher = self.teacher_models[teacher_batch.component_name] 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, - ) + teacher_pred = _compute_noise_pred(teacher, teacher_batch) # 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) + actor_forward_pred = None + actor_forward_batch = prepared_batches.actor_forward + if actor_forward_batch is not None: + with torch.no_grad(): + actor_forward_pred = _compute_noise_pred(actor_forward_batch.model, actor_forward_batch) + + new_pred = _compute_noise_pred(prepared.model, prepared) # 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) # 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) 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) # PEFT re-enables adapter gradients on exit; reshard first so that lands on the shards, not gathered copies. reshard_model(prepared.model) @@ -611,6 +601,9 @@ def _compute_noise_pred( old_pred=old_pred, ref_pred=ref_pred, teacher_pred=teacher_pred, + teacher_batch=teacher_batch, + actor_forward_pred=actor_forward_pred, + actor_forward_batch=actor_forward_batch, metrics=metrics, optim_step_idx=optim_step_idx, train_output_inputs=train_output_inputs, diff --git a/miles/backends/fsdp_utils/input_dtype_policy.py b/miles/backends/fsdp_utils/input_dtype_policy.py index ac15caa70..579132807 100644 --- a/miles/backends/fsdp_utils/input_dtype_policy.py +++ b/miles/backends/fsdp_utils/input_dtype_policy.py @@ -1,14 +1,17 @@ """Family-declared dtypes for the model-boundary inputs (latents, cond, timestep). -The trainer does not hard-cast its forward inputs; each family declares, per input, a dtype name -("fp32"/"bf16"/"fp16"), "default" for the run's forward dtype, or None to pass the rollout dtype -through. The boundary dtype is what element-wise ops see before any weight is involved, so it must -match what the family's sglang-d pipeline feeds the DiT for log-prob alignment; compute inside the -model is owned by the trainer's autocast (see model_loader.apply_fsdp2). +Each family declares, per input, a dtype name ("fp32"/"bf16"/"fp16"), "default" for the run's +forward dtype, or None to pass the rollout dtype through. The trainer resolves the policy once per +run (``InputDtypes.resolve``) and casts each stage's inputs with it as it sends them to the model +(``PreparedBatch.model_inputs``). The boundary dtype is what element-wise ops see before any weight +is involved, so it must match what the family's sglang-d pipeline feeds the DiT for log-prob +alignment; compute inside the model is owned by the trainer's autocast (see model_loader.apply_fsdp2). """ from __future__ import annotations +from dataclasses import dataclass + import torch _DTYPES = {"fp32": torch.float32, "bf16": torch.bfloat16, "fp16": torch.float16} @@ -16,39 +19,39 @@ INPUT_DTYPE_POLICY_KEYS = ("latents", "cond", "timestep") -def apply_input_dtype_policy( - policy: dict, - *, - latents: dict[str, torch.Tensor], - timesteps: dict[str, torch.Tensor], - conds: tuple, - default_dtype: torch.dtype, -) -> tuple[dict[str, torch.Tensor], dict[str, torch.Tensor], tuple]: - """Cast float boundary inputs per family policy ("default"/dtype name/None=passthrough); - autocast alone would leave element-wise ops running at the raw input dtype.""" - # A typo'd key would silently mean passthrough. - unknown = set(policy) - set(INPUT_DTYPE_POLICY_KEYS) - if unknown: - raise ValueError(f"input_dtype_policy has unknown keys {sorted(unknown)}; known: {INPUT_DTYPE_POLICY_KEYS}") - - def _dtype(key: str) -> torch.dtype | None: - dtype_name = policy.get(key) - if dtype_name is None: # passthrough: keep whatever dtype rollout handed us - return None - if dtype_name == "default": # the run's forward dtype - return default_dtype - if dtype_name not in _DTYPES: - raise ValueError(f"input_dtype_policy[{key!r}] has unknown dtype {dtype_name!r}") - return _DTYPES[dtype_name] - - def _cast(value, dtype: torch.dtype | None): - if dtype is None or not torch.is_tensor(value) or not value.is_floating_point(): - return value # passthrough inputs, int masks, and non-tensors stay untouched - return value.to(dtype) - - cond_dtype = _dtype("cond") - return ( - {name: _cast(latent, _dtype("latents")) for name, latent in latents.items()}, - {name: _cast(timestep, _dtype("timestep")) for name, timestep in timesteps.items()}, - tuple(cond and {key: _cast(value, cond_dtype) for key, value in cond.items()} for cond in conds), - ) +@dataclass(frozen=True) +class InputDtypes: + """A family's ``input_dtype_policy`` resolved for one run: the dtype each boundary input is sent in, None to + keep the rollout dtype.""" + + latents: torch.dtype | None + timestep: torch.dtype | None + cond: torch.dtype | None + + @classmethod + def resolve(cls, policy: dict, default_dtype: torch.dtype) -> InputDtypes: + # A typo'd key would silently mean passthrough. + unknown = set(policy) - set(INPUT_DTYPE_POLICY_KEYS) + if unknown: + raise ValueError( + f"input_dtype_policy has unknown keys {sorted(unknown)}; known: {INPUT_DTYPE_POLICY_KEYS}" + ) + + def _dtype(key: str) -> torch.dtype | None: + dtype_name = policy.get(key) + if dtype_name is None: # passthrough: keep whatever dtype rollout handed us + return None + if dtype_name == "default": # the run's forward dtype + return default_dtype + if dtype_name not in _DTYPES: + raise ValueError(f"input_dtype_policy[{key!r}] has unknown dtype {dtype_name!r}") + return _DTYPES[dtype_name] + + return cls(latents=_dtype("latents"), timestep=_dtype("timestep"), cond=_dtype("cond")) + + +def cast_input(value, dtype: torch.dtype | None): + """``value`` in ``dtype``; passthrough inputs, int masks and non-tensors stay untouched.""" + if dtype is None or not torch.is_tensor(value) or not value.is_floating_point(): + return value + return value.to(dtype) diff --git a/miles/backends/fsdp_utils/loss_hub/__init__.py b/miles/backends/fsdp_utils/loss_hub/__init__.py index 651570b37..818937a09 100644 --- a/miles/backends/fsdp_utils/loss_hub/__init__.py +++ b/miles/backends/fsdp_utils/loss_hub/__init__.py @@ -20,25 +20,28 @@ from miles.backends.fsdp_utils.loss_hub.flow_grpo import flow_grpo_loss_formula, prepare_flow_grpo_batch from miles.backends.fsdp_utils.loss_hub.nft import nft_loss_formula, prepare_nft_batch from miles.backends.fsdp_utils.loss_hub.sft import prepare_sft_batch, sft_loss_formula -from miles.backends.fsdp_utils.loss_hub.types import DiffusionLossContext, PreparedBatch +from miles.backends.fsdp_utils.loss_hub.types import DiffusionLossContext, PreparedBatch, PreparedBatches from miles.utils.misc import load_function -__all__ = ["LOSS_HOOKS", "DiffusionLossContext", "LossHooks", "PreparedBatch", "get_loss_hooks"] +__all__ = ["LOSS_HOOKS", "DiffusionLossContext", "LossHooks", "PreparedBatch", "PreparedBatches", "get_loss_hooks"] @dataclass(frozen=True) class LossHooks: """The hooks one trainer group runs on a rollout. - ``prepare(ctx, batch, *, microbatch_id, optim_step_idx, pad_to_len=None)`` builds a micro-batch's DiT inputs, - ``formula(ctx, batch, prepared, *, new_pred, old_pred, ref_pred, metrics, optim_step_idx, train_output_inputs, - ...)`` turns the predictions into its loss, ``train_input`` preprocesses the rank's train pairs before - micro-batching, and ``train_output(ctx, train_pairs, train_output_inputs)`` runs after the train steps and hands - its return value to the groups that train later; ``train_output_inputs`` is the list the formulas filled during - this train call. + ``prepare(ctx, batch, *, microbatch_id, optim_step_idx, pad_to_len=None) -> PreparedBatches`` builds a + micro-batch's stages: the training forward's input and, when the loss wants them, the teacher's and the actor's + extra no-grad forward's. ``formula(ctx, batch, prepared, *, new_pred, old_pred, ref_pred, teacher_pred, + teacher_batch, actor_forward_pred, actor_forward_batch, metrics, optim_step_idx, train_output_inputs, + write_old_log_prob, old_log_prob_from_new)`` turns the predictions into its loss, each stage's prediction next to + its batch (None for a stage the prepare hook did not ask for). ``train_input`` preprocesses the rank's train pairs + before micro-batching, and ``train_output(ctx, train_pairs, train_output_inputs)`` runs after the train steps and + hands its return value to the groups that train later; ``train_output_inputs`` is the list the formulas filled + during this train call. """ - prepare: Callable[..., PreparedBatch] + prepare: Callable[..., PreparedBatches] formula: Callable[..., torch.Tensor | None] train_input: Callable[[DiffusionLossContext, list], list] | None = None train_output: Callable[[DiffusionLossContext, list, list], Any] | None = None diff --git a/miles/backends/fsdp_utils/loss_hub/dmd2.py b/miles/backends/fsdp_utils/loss_hub/dmd2.py index 371679c19..f6f4024cd 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 draw and forward (the last step's actor-forward batch) before the critic trains that step on them, as +tianweiy/DMD2 does. +""" from __future__ import annotations @@ -6,8 +12,8 @@ import torch -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.loss_hub.sft import sft_batch, sft_loss_formula +from miles.backends.fsdp_utils.loss_hub.types import DiffusionLossContext, PreparedBatch, PreparedBatches from miles.backends.fsdp_utils.metrics import record_rollout_train_abs_diff, step_metric_key from miles.utils.metric_buffer import MetricBuffer @@ -19,25 +25,54 @@ def prepare_critic_batch( microbatch_id: int, optim_step_idx: int, pad_to_len: int | None = None, -) -> PreparedBatch: +) -> PreparedBatches: """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. + The last step's samples are scored at their noisy inputs. Under --dmd2-critic-scoring reuse-critic-step that step + trains on the scoring draw (grid points from the scoring range) with the teacher on the same inputs. Under + original it trains plain SFT, and the scoring draw is the teacher's and the critic's actor-forward input. """ - scoring = _is_scoring_step(ctx, optim_step_idx) - prepared = prepare_sft_batch( + if _is_scoring_step(ctx, optim_step_idx): + scoring = scoring_batch( + ctx, batch, microbatch_id=microbatch_id, optim_step_idx=optim_step_idx, pad_to_len=pad_to_len + ) + return PreparedBatches(actor=scoring, teacher=_teacher_batch(ctx, batch, scoring, pad_to_len=pad_to_len)) + sft = sft_batch( + ctx, _sft_pairs(ctx, batch), microbatch_id=microbatch_id, optim_step_idx=optim_step_idx, pad_to_len=pad_to_len + ) + if not _is_scored_before_training(ctx, optim_step_idx): + return PreparedBatches(actor=sft) + # Its own draw on this micro-batch, one no training forward shares. + scoring = scoring_batch( + ctx, batch, microbatch_id=microbatch_id, optim_step_idx=optim_step_idx, pad_to_len=pad_to_len, draw="scoring" + ) + return PreparedBatches( + actor=sft, teacher=_teacher_batch(ctx, batch, scoring, pad_to_len=pad_to_len), actor_forward=scoring + ) + + +def scoring_batch( + ctx: DiffusionLossContext, + batch: list[dict], + *, + microbatch_id: int, + optim_step_idx: int, + pad_to_len: int | None = None, + draw: str = "sample", +) -> PreparedBatch: + """The critic's SFT draw on the student's x0 at grid points in --dmd2-score-sigma-range.""" + return sft_batch( ctx, - _sft_batch(ctx, batch), + _sft_pairs(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), + draw=draw, ) - 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]: +def _sft_pairs(ctx: DiffusionLossContext, batch: list[dict]) -> list[dict]: config = ctx.train_pipeline_config return [ { @@ -55,15 +90,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( - ctx: DiffusionLossContext, batch: list[dict], prepared: PreparedBatch, *, pad_to_len: int | None +def _teacher_batch( + ctx: DiffusionLossContext, batch: list[dict], scoring: 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: ``scoring``'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( + scoring, 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( @@ -74,9 +112,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( @@ -88,6 +126,9 @@ 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, + teacher_batch: PreparedBatch | None = None, + actor_forward_pred: dict[str, torch.Tensor] | None = None, + actor_forward_batch: PreparedBatch | None = None, metrics: MetricBuffer, optim_step_idx: int, train_output_inputs: list, @@ -96,16 +137,18 @@ def critic_loss_formula( ) -> torch.Tensor: """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. + On the last step it also keeps the critic's and the teacher's x0 at each noisy input, before that step's update: + the critic's from the actor-forward batch when the step carries one, else from the training forward. """ - 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)) + if teacher_pred is not None: + if actor_forward_pred is None: + fake_batch, fake_pred = prepared, new_pred + else: + fake_batch, fake_pred = actor_forward_batch, actor_forward_pred + keep_scores(batch, fake_batch, fake_pred, 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))) # 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 +168,26 @@ def critic_loss_formula( ) +def keep_scores( + batch: list[dict], + 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, 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)) + + def score_last_step_samples( ctx: DiffusionLossContext, train_pairs: list[dict], train_output_inputs: list ) -> dict[int, dict]: @@ -133,7 +196,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 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 def select_scored_pairs(ctx: DiffusionLossContext, train_pairs: list[dict]) -> list[dict]: @@ -154,6 +223,22 @@ def prepare_generator_batch( microbatch_id: int, optim_step_idx: int, pad_to_len: int | None = None, +) -> PreparedBatches: + """The student's hook: one stage, its training forward on ``generator_batch``.""" + return PreparedBatches( + actor=generator_batch( + ctx, batch, microbatch_id=microbatch_id, optim_step_idx=optim_step_idx, pad_to_len=pad_to_len + ) + ) + + +def generator_batch( + ctx: DiffusionLossContext, + batch: list[dict], + *, + microbatch_id: int, + optim_step_idx: int, + pad_to_len: int | None = None, ) -> PreparedBatch: """The student's step ``i`` on its own rollout input ``x_i``, unguided. @@ -197,6 +282,9 @@ def dmd2_loss_formula( old_pred: dict[str, torch.Tensor] | None, ref_pred: dict[str, torch.Tensor] | None, teacher_pred: dict[str, torch.Tensor] | None = None, + teacher_batch: PreparedBatch | None = None, + actor_forward_pred: dict[str, torch.Tensor] | None = None, + actor_forward_batch: PreparedBatch | 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 ffddf3ba3..a99a8cee8 100644 --- a/miles/backends/fsdp_utils/loss_hub/flow_grpo.py +++ b/miles/backends/fsdp_utils/loss_hub/flow_grpo.py @@ -9,7 +9,7 @@ import torch from miles.backends.fsdp_utils.loss_hub.score_centering import score_centering_term -from miles.backends.fsdp_utils.loss_hub.types import DiffusionLossContext, PreparedBatch +from miles.backends.fsdp_utils.loss_hub.types import DiffusionLossContext, PreparedBatch, PreparedBatches from miles.backends.fsdp_utils.metrics import record_prev_mean_diff_over_noise_std, record_rollout_train_abs_diff from miles.utils.metric_buffer import MetricBuffer from miles.utils.train_data_utils import stack_train_pair_rollout_debug @@ -41,7 +41,7 @@ def _combine_streams(value_by_stream: dict[str, torch.Tensor], stream_weights: d ) -def prepare_flow_grpo_batch( +def flow_grpo_batch( ctx: DiffusionLossContext, batch: list[dict], *, @@ -141,6 +141,22 @@ def prepare_flow_grpo_batch( ) +def prepare_flow_grpo_batch( + ctx: DiffusionLossContext, + batch: list[dict], + *, + microbatch_id: int, + optim_step_idx: int, + pad_to_len: int | None = None, +) -> PreparedBatches: + """The Flow-GRPO hook: one stage, the training forward on the stacked SDE pairs.""" + return PreparedBatches( + actor=flow_grpo_batch( + ctx, batch, microbatch_id=microbatch_id, optim_step_idx=optim_step_idx, pad_to_len=pad_to_len + ) + ) + + def flow_grpo_loss_formula( ctx: DiffusionLossContext, batch: list[dict], @@ -150,6 +166,9 @@ def flow_grpo_loss_formula( old_pred: dict[str, torch.Tensor] | None, ref_pred: dict[str, torch.Tensor] | None, teacher_pred: dict[str, torch.Tensor] | None = None, + teacher_batch: PreparedBatch | None = None, + actor_forward_pred: dict[str, torch.Tensor] | None = None, + actor_forward_batch: PreparedBatch | 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 33133bb86..96e5a9fe0 100644 --- a/miles/backends/fsdp_utils/loss_hub/nft.py +++ b/miles/backends/fsdp_utils/loss_hub/nft.py @@ -4,7 +4,7 @@ import torch -from miles.backends.fsdp_utils.loss_hub.types import DiffusionLossContext, PreparedBatch +from miles.backends.fsdp_utils.loss_hub.types import DiffusionLossContext, PreparedBatch, PreparedBatches from miles.utils.hash_utils import stable_hash from miles.utils.metric_buffer import MetricBuffer @@ -20,7 +20,7 @@ def corrupt(x0: torch.Tensor, t: torch.Tensor, eps: torch.Tensor) -> torch.Tenso return (1.0 - t) * x0 + t * eps -def prepare_nft_batch( +def nft_batch( ctx: DiffusionLossContext, batch: list[dict], *, @@ -66,6 +66,20 @@ def prepare_nft_batch( ) +def prepare_nft_batch( + ctx: DiffusionLossContext, + batch: list[dict], + *, + microbatch_id: int, + optim_step_idx: int, + pad_to_len: int | None = None, +) -> PreparedBatches: + """The NFT hook: one stage, the training forward on ``nft_batch``'s corruption.""" + return PreparedBatches( + actor=nft_batch(ctx, batch, microbatch_id=microbatch_id, optim_step_idx=optim_step_idx, pad_to_len=pad_to_len) + ) + + def nft_r_from_advantages(advantages: torch.Tensor, *, adv_clip_max: float) -> torch.Tensor: clip = float(adv_clip_max) adv_clipped = torch.clamp(advantages, -clip, clip) @@ -114,6 +128,9 @@ def nft_loss_formula( old_pred: dict[str, torch.Tensor] | None, ref_pred: dict[str, torch.Tensor] | None, teacher_pred: dict[str, torch.Tensor] | None = None, + teacher_batch: PreparedBatch | None = None, + actor_forward_pred: dict[str, torch.Tensor] | None = None, + actor_forward_batch: PreparedBatch | 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 9fb0a5552..9a35e78b6 100644 --- a/miles/backends/fsdp_utils/loss_hub/sft.py +++ b/miles/backends/fsdp_utils/loss_hub/sft.py @@ -5,7 +5,12 @@ import torch import torch.nn as nn -from miles.backends.fsdp_utils.loss_hub.types import DiffusionLossContext, FlowNoiseSchedule, PreparedBatch +from miles.backends.fsdp_utils.loss_hub.types import ( + DiffusionLossContext, + FlowNoiseSchedule, + PreparedBatch, + PreparedBatches, +) from miles.backends.fsdp_utils.metrics import sigma_bucket_key from miles.utils.hash_utils import stable_hash from miles.utils.metric_buffer import MetricBuffer @@ -34,7 +39,7 @@ def select_component( return component_name, model, torch.tensor(served, device=device) -def prepare_sft_batch( +def sft_batch( ctx: DiffusionLossContext, batch: list[dict], *, @@ -42,13 +47,15 @@ def prepare_sft_batch( optim_step_idx: int, pad_to_len: int | None = None, grid_index_range: tuple[int, int] | None = None, + draw: str = "sample", ) -> PreparedBatch: """Corrupt every latent stream at one shared grid index, each through its own shifted grid; CFG-free cached cond. The visual grid picks the DiT component and the index is drawn uniformly from the points it serves, within ``grid_index_range`` (inclusive) when given. Sharing the index pairs the streams' sigmas as inference steps them, - one step index read through each stream's shift. ``microbatch_id`` seeds the draws; ``optim_step_idx`` is part of - every prepare hook's signature and unused here. + one step index read through each stream's shift. ``microbatch_id`` seeds the draws and ``draw`` names the draw: + a second draw on the same micro-batch (DMD2's scoring draw) passes its own name and gets its own noise. + ``optim_step_idx`` is part of every prepare hook's signature and unused here. """ device = ctx.device config = ctx.train_pipeline_config @@ -69,7 +76,7 @@ def prepare_sft_batch( # The visual stream keeps the single-stream seed, so single-stream runs draw as before; other streams add their # name, so adding a stream never changes another stream's noise. - seed_parts = ("sample", int(ctx.args.seed), ctx.rollout_id, microbatch_id, ctx.dp_rank) + seed_parts = (draw, int(ctx.args.seed), ctx.rollout_id, microbatch_id, ctx.dp_rank) generators = { stream_name: torch.Generator(device=device).manual_seed( stable_hash(*seed_parts) if stream_name == "visual" else stable_hash(*seed_parts, stream_name) @@ -119,6 +126,20 @@ def prepare_sft_batch( ) +def prepare_sft_batch( + ctx: DiffusionLossContext, + batch: list[dict], + *, + microbatch_id: int, + optim_step_idx: int, + pad_to_len: int | None = None, +) -> PreparedBatches: + """The SFT hook: one stage, the training forward on ``sft_batch``'s draw.""" + return PreparedBatches( + actor=sft_batch(ctx, batch, microbatch_id=microbatch_id, optim_step_idx=optim_step_idx, pad_to_len=pad_to_len) + ) + + def sft_loss_formula( ctx: DiffusionLossContext, batch: list[dict], @@ -128,6 +149,9 @@ def sft_loss_formula( old_pred: dict[str, torch.Tensor] | None, ref_pred: dict[str, torch.Tensor] | None, teacher_pred: dict[str, torch.Tensor] | None = None, + teacher_batch: PreparedBatch | None = None, + actor_forward_pred: dict[str, torch.Tensor] | None = None, + actor_forward_batch: PreparedBatch | 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 235b7bf7e..0fe37b8a7 100644 --- a/miles/backends/fsdp_utils/loss_hub/types.py +++ b/miles/backends/fsdp_utils/loss_hub/types.py @@ -9,6 +9,8 @@ import torch import torch.nn as nn +from miles.backends.fsdp_utils.input_dtype_policy import InputDtypes, cast_input + @dataclass(frozen=True, eq=False) class DiffusionLossContext: @@ -50,7 +52,7 @@ def shifted(cls, shift: float, num_train_timesteps: int) -> FlowNoiseSchedule: @dataclass class PreparedBatch: - """Actor-owned DiT forward inputs produced by a prepare hook. + """One stage's DiT forward input, built by a prepare hook. ``latents`` and both timestep fields are keyed by latent stream name: "visual", plus e.g. "audio" for joint audio-video models. The DiT prediction comes back keyed the same way. @@ -70,5 +72,36 @@ 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 + + def model_inputs(self, input_dtypes: InputDtypes) -> dict[str, Any]: + """What the forward sends the model: the latents, model timesteps and conds cast per ``input_dtypes``, under + ``compute_noise_pred``'s kwarg names. The raw fields stay as rollout handed them, for the formulas.""" + + def cond(value: dict | None) -> dict | None: + return None if value is None else {key: cast_input(item, input_dtypes.cond) for key, item in value.items()} + + return { + "latents_input": {name: cast_input(x, input_dtypes.latents) for name, x in self.latents.items()}, + "timesteps_input": { + name: cast_input(t, input_dtypes.timestep) for name, t in self.timesteps_for_model.items() + }, + "pos_cond": cond(self.pos_cond), + "neg_cond": cond(self.neg_cond), + "joint_cond": cond(self.joint_cond), + } + + +@dataclass(frozen=True, eq=False) +class PreparedBatches: + """The stages of one micro-batch, as the prepare hook returns them. + + ``actor`` is the training forward's input; the EMA and reference forwards take it too. ``teacher`` is the frozen + teacher's input with its own CFG fields: the trunk runs the teacher loaded by --teacher-load for its + ``component_name`` on it (its ``model`` field is not read). ``actor_forward`` is a second, no-grad forward of the + actor's model. Each stage's prediction reaches the formula next to its batch: ``new_pred``; ``teacher_pred`` and + ``teacher_batch``; ``actor_forward_pred`` and ``actor_forward_batch``. + """ + + actor: PreparedBatch + teacher: PreparedBatch | None = None + actor_forward: PreparedBatch | None = None diff --git a/miles/utils/arguments.py b/miles/utils/arguments.py index eb48351e9..2f86c0ebe 100644 --- a/miles/utils/arguments.py +++ b/miles/utils/arguments.py @@ -1028,8 +1028,10 @@ def add_algo_arguments(parser): default=None, help=( "Dotted path to prepare hook " - "`fn(ctx, batch, *, microbatch_id, optim_step_idx, pad_to_len=None) -> PreparedBatch`. " - "Builds DiT inputs; --loss-type custom_loss only, default is Flow-GRPO SDE-pair stacking." + "`fn(ctx, batch, *, microbatch_id, optim_step_idx, pad_to_len=None) -> PreparedBatches`. " + "Builds the micro-batch's stages (the training forward's input, plus the teacher's and the actor's " + "extra no-grad forward's when the loss wants them); --loss-type custom_loss only, default is " + "Flow-GRPO SDE-pair stacking." ), ) parser.add_argument( @@ -1038,7 +1040,8 @@ def add_algo_arguments(parser): default=None, help=( "Dotted path to a loss *formula* only: " - "`fn(ctx, batch, prepared, *, new_pred, ref_pred, metrics, ...) -> Tensor`. " + "`fn(ctx, batch, prepared, *, new_pred, old_pred, ref_pred, teacher_pred, teacher_batch, " + "actor_forward_pred, actor_forward_batch, metrics, ...) -> Tensor`. " "--loss-type custom_loss only, default is Flow-GRPO's. " "DiT forward is owned by the actor; this hook only computes the objective." ), @@ -1124,6 +1127,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_h3_streams.py b/tests/fast/backends/fsdp_utils/test_h3_streams.py index fa13557e0..d9d8fed42 100644 --- a/tests/fast/backends/fsdp_utils/test_h3_streams.py +++ b/tests/fast/backends/fsdp_utils/test_h3_streams.py @@ -56,7 +56,7 @@ from torch import nn from miles.backends.fsdp_utils.configs.h3 import H3TrainPipelineConfig -from miles.backends.fsdp_utils.loss_hub.sft import prepare_sft_batch, sft_loss_formula +from miles.backends.fsdp_utils.loss_hub.sft import sft_batch, sft_loss_formula from miles.backends.fsdp_utils.loss_hub.types import DiffusionLossContext from miles.backends.fsdp_utils.metrics import new_metric_buffer from miles.backends.fsdp_utils.mixed_precision import compile_param_dtype_maps @@ -104,7 +104,7 @@ def test_t2va_prediction_matches_the_sft_target_and_skips_padding_rows(): device=torch.device("cpu"), ) batch = [{"latent": {"visual": torch.ones(3, 96)}, "cond_kwargs": cond}] - prepared = prepare_sft_batch(context, batch, microbatch_id=0, optim_step_idx=0) + prepared = sft_batch(context, batch, microbatch_id=0, optim_step_idx=0) prediction = config.compute_noise_pred( model=context.models["transformer"], latents_input=prepared.latents, @@ -413,7 +413,7 @@ def test_real_tiny_diffusers_h3_joint_sft_forward_and_backward(forward_dtype): forward_dtype=forward_dtype, device=torch.device("cpu"), ) - prepared = prepare_sft_batch(context, batch, microbatch_id=0, optim_step_idx=0) + prepared = sft_batch(context, batch, microbatch_id=0, optim_step_idx=0) autocast_enabled = forward_dtype != torch.float32 and config.enable_autocast with torch.autocast("cpu", dtype=forward_dtype, enabled=autocast_enabled): prediction = config.compute_noise_pred( diff --git a/tests/fast/backends/fsdp_utils/test_input_dtype_policy.py b/tests/fast/backends/fsdp_utils/test_input_dtype_policy.py index 46e9b17cf..d446a142c 100644 --- a/tests/fast/backends/fsdp_utils/test_input_dtype_policy.py +++ b/tests/fast/backends/fsdp_utils/test_input_dtype_policy.py @@ -1,76 +1,106 @@ +"""The family's input_dtype_policy, resolved once per run, casts each stage's inputs as the trainer sends them. + + policy {"latents"/"timestep"/"cond": "default" | "fp32"/"bf16"/"fp16" | None} --resolve(forward dtype)--> InputDtypes + PreparedBatch.model_inputs(InputDtypes) --> compute_noise_pred kwargs, floats cast, int masks and the raw batch untouched + a batch derived by dataclasses.replace (DMD2's teacher) casts whatever it holds when it is read +""" + from tests.ci.ci_register import register_cpu_ci register_cpu_ci(est_time=10, suite="stage-a-cpu", labels=[]) +import dataclasses + import pytest import torch from miles.backends.fsdp_utils.configs.train_pipeline_config import TrainPipelineConfig -from miles.backends.fsdp_utils.input_dtype_policy import apply_input_dtype_policy +from miles.backends.fsdp_utils.input_dtype_policy import InputDtypes +from miles.backends.fsdp_utils.loss_hub.types import PreparedBatch, PreparedBatches DEFAULT_POLICY = TrainPipelineConfig.input_dtype_policy +CAST_POLICY = {"latents": "default", "cond": None, "timestep": "fp32"} -def _inputs(): - latents = torch.zeros(1, 4, 8, dtype=torch.float32) - timesteps = torch.tensor([857.69], dtype=torch.float32) +def _prepared(**overrides): pos_cond = { "context": torch.zeros(1, 3, 8, dtype=torch.float32), "context_mask": torch.ones(1, 3, dtype=torch.int64), } - return {"visual": latents}, {"visual": timesteps}, pos_cond - - -def test_default_policy_is_passthrough(): - latents, timesteps, pos_cond = _inputs() - out_latents, out_timesteps, (out_pos, out_neg, out_joint) = apply_input_dtype_policy( - DEFAULT_POLICY, - latents=latents, + timesteps = {"visual": torch.tensor([857.69], dtype=torch.float32)} + fields = dict( + latents={"visual": torch.zeros(1, 4, 8, dtype=torch.float32)}, timesteps=timesteps, - conds=(pos_cond, None, None), - default_dtype=torch.bfloat16, + timesteps_for_model=timesteps, + model=torch.nn.Identity(), + component_name="transformer", + guidance_scale=1.0, + use_cfg=False, + cfg_batching=False, + true_cfg_scale=None, + pos_cond=pos_cond, + neg_cond=None, + joint_cond=None, + advantage=torch.zeros(1), ) - assert out_latents["visual"].dtype == torch.float32 - assert out_timesteps["visual"].dtype == torch.float32 - assert out_pos["context"].dtype == torch.float32 - assert out_pos["context_mask"].dtype == torch.int64 - assert out_neg is None and out_joint is None - - -def test_family_override_timestep_default(): - latents, timesteps, pos_cond = _inputs() - policy = {**DEFAULT_POLICY, "timestep": "default"} - _, out_timesteps, _ = apply_input_dtype_policy( - policy, - latents=latents, - timesteps=timesteps, - conds=(pos_cond, None, None), - default_dtype=torch.bfloat16, + return PreparedBatch(**{**fields, **overrides}) + + +def test_the_default_policy_is_passthrough(): + assert InputDtypes.resolve(DEFAULT_POLICY, torch.bfloat16) == InputDtypes(None, None, None) + sent = _prepared().model_inputs(InputDtypes.resolve(DEFAULT_POLICY, torch.bfloat16)) + assert sent["latents_input"]["visual"].dtype == torch.float32 + assert sent["timesteps_input"]["visual"].dtype == torch.float32 + assert sent["pos_cond"]["context"].dtype == torch.float32 + assert sent["neg_cond"] is None and sent["joint_cond"] is None + + +def test_default_resolves_to_the_forward_dtype_and_names_to_their_dtype(): + assert InputDtypes.resolve({**DEFAULT_POLICY, "timestep": "default"}, torch.bfloat16).timestep == torch.bfloat16 + assert InputDtypes.resolve(CAST_POLICY, torch.bfloat16) == InputDtypes(torch.bfloat16, torch.float32, None) + + +def test_the_cast_touches_floats_only_and_leaves_the_batch_as_it_was(): + prepared = _prepared() + sent = prepared.model_inputs( + InputDtypes.resolve({"latents": "default", "cond": "default", "timestep": "fp32"}, torch.bfloat16) ) - assert out_timesteps["visual"].dtype == torch.bfloat16 + assert sent["latents_input"]["visual"].dtype == torch.bfloat16 + assert sent["timesteps_input"]["visual"].dtype == torch.float32 + assert sent["pos_cond"]["context"].dtype == torch.bfloat16 + assert sent["pos_cond"]["context_mask"].dtype == torch.int64 + # The formulas read the batch: it keeps the rollout dtypes. + assert prepared.latents["visual"].dtype == torch.float32 and prepared.pos_cond["context"].dtype == torch.float32 -def test_cast_policy_casts_floats_only(): - latents, timesteps, pos_cond = _inputs() - out_latents, _, (out_pos, _, _) = apply_input_dtype_policy( - {"latents": "default", "cond": "default", "timestep": "fp32"}, - latents=latents, - timesteps=timesteps, - conds=(pos_cond, None, None), - default_dtype=torch.bfloat16, +def test_a_batch_derived_by_replace_casts_what_it_holds_when_read(): + # DMD2 derives the teacher's batch from the scoring batch by swapping conds; the cast happens on send, so the + # new conds are what gets cast. + teacher = dataclasses.replace( + _prepared(), use_cfg=True, neg_cond={"context": torch.zeros(1, 3, 8, dtype=torch.float32)} + ) + sent = teacher.model_inputs( + InputDtypes.resolve({"latents": None, "cond": "default", "timestep": None}, torch.bfloat16) ) - assert out_latents["visual"].dtype == torch.bfloat16 - assert out_pos["context"].dtype == torch.bfloat16 - assert out_pos["context_mask"].dtype == torch.int64 + assert sent["neg_cond"]["context"].dtype == torch.bfloat16 and sent["pos_cond"]["context"].dtype == torch.bfloat16 + assert sent["latents_input"]["visual"].dtype == torch.float32 + + +def test_every_stage_is_cast_the_same_way(): + stages = PreparedBatches(actor=_prepared(), teacher=_prepared(use_cfg=True), actor_forward=_prepared()) + input_dtypes = InputDtypes.resolve(CAST_POLICY, torch.bfloat16) + for batch in (stages.actor, stages.teacher, stages.actor_forward): + sent = batch.model_inputs(input_dtypes) + assert sent["latents_input"]["visual"].dtype == torch.bfloat16 + assert sent["timesteps_input"]["visual"].dtype == torch.float32 + assert sent["pos_cond"]["context"].dtype == torch.float32 def test_unknown_key_rejected(): - latents, timesteps, pos_cond = _inputs() with pytest.raises(ValueError, match="unknown keys"): - apply_input_dtype_policy( - {"latnets": "default"}, - latents=latents, - timesteps=timesteps, - conds=(pos_cond, None, None), - default_dtype=torch.bfloat16, - ) + InputDtypes.resolve({"latnets": "default"}, torch.bfloat16) + + +def test_unknown_dtype_name_rejected(): + with pytest.raises(ValueError, match="unknown dtype"): + InputDtypes.resolve({"latents": "fp8"}, torch.bfloat16) 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 99d74a47f..9e42a67a5 100644 --- a/tests/fast/backends/fsdp_utils/test_loss_hub_dmd2.py +++ b/tests/fast/backends/fsdp_utils/test_loss_hub_dmd2.py @@ -2,13 +2,13 @@ rollout pair: x0 = the student's x0 prediction at its stop step i, denoising_env = the rollout cond │ - prepare_critic_batch ──► prepare_sft_batch on {"latent": {"visual": x0}, "cond_kwargs": prepared pos cond} + prepare_critic_batch ──► sft_batch on {"latent": {"visual": x0}, "cond_kwargs": prepared pos cond} (the critic's K steps are the SFT loss on the student's samples; the last step, whose samples get scored, draws grid points whose unshifted sigma lies in --dmd2-score-sigma-range, default [0.02, 0.98]) │ - 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 stage, PreparedBatches.teacher, 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 │ @@ -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 carries the scoring batch, a fresh draw in the +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_at_its_own_draw + 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 """ from tests.ci.ci_register import register_cpu_ci @@ -61,7 +68,7 @@ import miles.backends.fsdp_utils.loss_hub.dmd2 as dmd2 from miles.backends.fsdp_utils.configs.sd3 import SD3TrainPipelineConfig -from miles.backends.fsdp_utils.loss_hub.sft import prepare_sft_batch, sft_loss_formula +from miles.backends.fsdp_utils.loss_hub.sft import sft_batch, sft_loss_formula from miles.backends.fsdp_utils.loss_hub.types import DiffusionLossContext, FlowNoiseSchedule from miles.backends.fsdp_utils.metrics import new_metric_buffer from miles.utils.train_data_utils import build_microbatch_schedule @@ -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"), @@ -156,36 +164,37 @@ 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 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(model, prepared): + return _forward( + config, + model, + prepared, + use_cfg=prepared.use_cfg, + cfg_batching=prepared.cfg_batching, + guidance_scale=prepared.guidance_scale, + ) + 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( + prepared_batches = dmd2.prepare_critic_batch( ctx, batch, microbatch_id=optim_step_idx * 10 + start, optim_step_idx=optim_step_idx ) + prepared = prepared_batches.actor teacher_pred = None - if prepared.teacher_guidance_scale is not None: - use_cfg = prepared.teacher_guidance_scale > 1.0 + if prepared_batches.teacher is not None: 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, - ) + teacher_pred = forward(teacher, prepared_batches.teacher) + actor_forward_pred = None + if prepared_batches.actor_forward is not None: + with torch.no_grad(): + actor_forward_pred = forward(prepared.model, prepared_batches.actor_forward) + new_pred = forward(prepared.model, prepared) loss = dmd2.critic_loss_formula( ctx, batch, @@ -194,11 +203,14 @@ def _critic_step(ctx, pairs, optim_step_idx, train_output_inputs, metrics=None, old_pred=None, ref_pred=None, teacher_pred=teacher_pred, + teacher_batch=prepared_batches.teacher, + actor_forward_pred=actor_forward_pred, + actor_forward_batch=prepared_batches.actor_forward, metrics=metrics or _Metrics(), optim_step_idx=optim_step_idx, train_output_inputs=train_output_inputs, ) - steps.append((batch, prepared, new_pred, loss)) + steps.append((batch, prepared_batches, new_pred, loss)) return steps @@ -218,14 +230,14 @@ def test_critic_batch_is_the_sft_batch_on_the_student_x0(): pairs = _pairs(3) for optim_step_idx in range(CRITIC_STEPS - 1): - critic_batch = dmd2.prepare_critic_batch(ctx, pairs, microbatch_id=0, optim_step_idx=optim_step_idx) - sft_batch = prepare_sft_batch(ctx, _sft_pairs(ctx, pairs), microbatch_id=0, optim_step_idx=optim_step_idx) + critic_batch = dmd2.prepare_critic_batch(ctx, pairs, microbatch_id=0, optim_step_idx=optim_step_idx).actor + expected = sft_batch(ctx, _sft_pairs(ctx, pairs), microbatch_id=0, optim_step_idx=optim_step_idx) assert critic_batch.model is ctx.models["transformer"] for field in ("latents", "timesteps", "timesteps_for_model"): - assert torch.equal(getattr(critic_batch, field)["visual"], getattr(sft_batch, field)["visual"]) - assert torch.equal(critic_batch.extras["target"]["visual"], sft_batch.extras["target"]["visual"]) - assert torch.equal(critic_batch.pos_cond["encoder_hidden_states"], sft_batch.pos_cond["encoder_hidden_states"]) + assert torch.equal(getattr(critic_batch, field)["visual"], getattr(expected, field)["visual"]) + assert torch.equal(critic_batch.extras["target"]["visual"], expected.extras["target"]["visual"]) + assert torch.equal(critic_batch.pos_cond["encoder_hidden_states"], expected.pos_cond["encoder_hidden_states"]) assert not critic_batch.use_cfg @@ -234,18 +246,18 @@ def test_last_step_draws_from_the_scoring_range(): 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( + critic_batch = dmd2.prepare_critic_batch(ctx, pairs, microbatch_id=0, optim_step_idx=last_step).actor + expected = sft_batch( ctx, _sft_pairs(ctx, pairs), microbatch_id=0, optim_step_idx=last_step, grid_index_range=(20, 980) ) - assert torch.equal(critic_batch.latents["visual"], sft_batch.latents["visual"]) - assert torch.equal(critic_batch.extras["target"]["visual"], sft_batch.extras["target"]["visual"]) + assert torch.equal(critic_batch.latents["visual"], expected.latents["visual"]) + assert torch.equal(critic_batch.extras["target"]["visual"], expected.extras["target"]["visual"]) grid = FlowNoiseSchedule.shifted(FLOW_SHIFT, 1000).sigmas sigmas = critic_batch.extras["sigmas"]["visual"] assert set(sigmas.tolist()) <= set(grid[20:981].tolist()) # The same draw without the range leaves it, so the restriction is exercised. - unrestricted = prepare_sft_batch(ctx, _sft_pairs(ctx, pairs), microbatch_id=0, optim_step_idx=last_step) + unrestricted = sft_batch(ctx, _sft_pairs(ctx, pairs), microbatch_id=0, optim_step_idx=last_step) assert not set(unrestricted.extras["sigmas"]["visual"].tolist()) <= set(grid[20:981].tolist()) @@ -255,14 +267,14 @@ def test_score_sigma_range_bounds_the_unshifted_sigma(): pairs = _pairs(256) last_step = CRITIC_STEPS - 1 - critic_batch = dmd2.prepare_critic_batch(ctx, pairs, microbatch_id=0, optim_step_idx=last_step) + critic_batch = dmd2.prepare_critic_batch(ctx, pairs, microbatch_id=0, optim_step_idx=last_step).actor # Grid index i carries the unshifted sigma 1 - i / 1000, so [0.1, 0.5] is grid points [500, 900]. - sft_batch = prepare_sft_batch( + expected = sft_batch( ctx, _sft_pairs(ctx, pairs), microbatch_id=0, optim_step_idx=last_step, grid_index_range=(500, 900) ) sigmas = critic_batch.extras["sigmas"]["visual"] - assert torch.equal(sigmas, sft_batch.extras["sigmas"]["visual"]) + assert torch.equal(sigmas, expected.extras["sigmas"]["visual"]) unshifted = sigmas / (FLOW_SHIFT - (FLOW_SHIFT - 1) * sigmas) assert unshifted.min() >= 0.1 - 1e-6 and unshifted.max() <= 0.5 + 1e-6 @@ -272,11 +284,11 @@ def test_critic_loss_is_the_sft_loss(): ctx = _ctx() metrics = _Metrics() sft_metrics = _Metrics() - for batch, prepared, new_pred, loss in _critic_step(ctx, _pairs(3), optim_step_idx, [], metrics): + for batch, prepared_batches, new_pred, loss in _critic_step(ctx, _pairs(3), optim_step_idx, [], metrics): sft_loss = sft_loss_formula( ctx, batch, - prepared, + prepared_batches.actor, new_pred=new_pred, old_pred=None, ref_pred=None, @@ -293,7 +305,8 @@ def test_x0_critic_loss_weights_the_velocity_mse(): ctx = _ctx() ctx.models["transformer"] = _NoisyInputVelocity() ctx.args.dmd2_critic_loss_space = "x0" - for batch, prepared, new_pred, loss in _critic_step(ctx, _pairs(3), optim_step_idx, []): + for batch, prepared_batches, new_pred, loss in _critic_step(ctx, _pairs(3), optim_step_idx, []): + prepared = prepared_batches.actor x_s = prepared.latents["visual"] sigma = prepared.extras["sigmas"]["visual"].view(-1, 1, 1, 1) x0 = torch.stack([pair["x0"] for pair in batch]) @@ -322,9 +335,9 @@ def test_only_the_last_step_keeps_scoring_inputs(): 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 + prepared_batches = dmd2.prepare_critic_batch(ctx, _pairs(2), microbatch_id=0, optim_step_idx=optim_step_idx) + assert prepared_batches.teacher is None + assert prepared_batches.actor.neg_cond is None and prepared_batches.actor.joint_cond is None @pytest.mark.parametrize("cfg_batching", [False, True]) @@ -334,31 +347,42 @@ def test_last_step_asks_for_the_guided_teacher(cfg_batching): config.cfg_batching = cfg_batching pairs = _pairs(2) - prepared = dmd2.prepare_critic_batch(ctx, pairs, microbatch_id=0, optim_step_idx=CRITIC_STEPS - 1) + prepared_batches = dmd2.prepare_critic_batch(ctx, pairs, microbatch_id=0, optim_step_idx=CRITIC_STEPS - 1) + prepared = prepared_batches.actor - 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_batches.teacher + 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(): ctx = _ctx(teacher_guidance_scale=1.0) - prepared = dmd2.prepare_critic_batch( + prepared_batches = 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_batches.teacher + 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(): @@ -379,7 +403,8 @@ def test_scores_are_x0_at_the_kept_input(): scores = dmd2.score_last_step_samples(ctx, pairs, inputs) assert list(scores) == [100, 101, 102, 103, 104] - for batch, prepared, _, _ in steps: + for batch, prepared_batches, _, _ in steps: + prepared = prepared_batches.actor x_s = prepared.latents["visual"] velocity = x_s + prepared.timesteps_for_model["visual"].view(-1, 1, 1, 1) sigma = prepared.extras["sigmas"]["visual"].view(-1, 1, 1, 1) @@ -394,9 +419,10 @@ def test_teacher_runs_cfg_and_the_critic_runs_unguided(): pairs = _pairs(2) inputs = [] - [(_, prepared, _, loss)] = _critic_step(ctx, pairs, CRITIC_STEPS - 1, inputs, teacher=teacher) + [(_, prepared_batches, _, loss)] = _critic_step(ctx, pairs, CRITIC_STEPS - 1, inputs, teacher=teacher) scores = dmd2.score_last_step_samples(ctx, pairs, inputs) + prepared = prepared_batches.actor x_s = prepared.latents["visual"] sigma = prepared.extras["sigmas"]["visual"].view(-1, 1, 1, 1) for n, pair in enumerate(pairs): @@ -457,7 +483,7 @@ def _metrics(): def _loss(ctx, pairs, x0): """dmd2_loss_formula with the student predicting ``x0`` from each pair's rollout input.""" - prepared = dmd2.prepare_generator_batch(ctx, pairs, microbatch_id=0, optim_step_idx=0) + prepared = dmd2.generator_batch(ctx, pairs, microbatch_id=0, optim_step_idx=0) sigmas = prepared.extras["sigmas"].view(-1, 1, 1, 1) new_pred = {"visual": (prepared.latents["visual"] - x0) / sigmas} metrics = _metrics() @@ -488,7 +514,7 @@ def test_generator_batch_is_the_student_step_on_its_input(): ctx = _ctx() pairs = _generator_pairs(2) - prepared = dmd2.prepare_generator_batch(ctx, pairs, microbatch_id=0, optim_step_idx=0) + prepared = dmd2.generator_batch(ctx, pairs, microbatch_id=0, optim_step_idx=0) assert prepared.model is ctx.models["transformer"] assert torch.equal(prepared.latents["visual"], torch.stack([pair["latent"] for pair in pairs]).float()) @@ -604,3 +630,109 @@ 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 _original_ctx(teacher_guidance_scale=3.0): + ctx = _ctx(teacher_guidance_scale) + ctx.args.dmd2_critic_scoring = "original" + return ctx + + +def test_under_original_only_the_last_step_carries_a_scoring_batch_and_it_stays_plain_sft(): + ctx = _original_ctx() + pairs = _pairs(256) + last_step = CRITIC_STEPS - 1 + + critic_batches = dmd2.prepare_critic_batch(ctx, pairs, microbatch_id=6, optim_step_idx=last_step) + + expected = sft_batch(ctx, _sft_pairs(ctx, pairs), microbatch_id=6, optim_step_idx=last_step) + assert torch.equal(critic_batches.actor.latents["visual"], expected.latents["visual"]) + assert torch.equal(critic_batches.actor.extras["target"]["visual"], expected.extras["target"]["visual"]) + assert critic_batches.actor.neg_cond is None and critic_batches.actor.joint_cond is None + # The teacher and the critic's actor forward both run on the scoring draw. + assert torch.equal(critic_batches.teacher.latents["visual"], critic_batches.actor_forward.latents["visual"]) + first_step = dmd2.prepare_critic_batch(ctx, pairs, microbatch_id=0, optim_step_idx=0) + assert first_step.teacher is None and first_step.actor_forward is None + + +@pytest.mark.parametrize("cfg_batching", [False, True]) +def test_the_scoring_batch_is_the_reuse_last_step_batch_at_its_own_draw(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) + + original_ctx = _original_ctx() + original_ctx.train_pipeline_config.cfg_batching = cfg_batching + # The same micro-batch id: the scoring draw is named, not numbered past the training ids. + original = dmd2.prepare_critic_batch(original_ctx, pairs, microbatch_id=9, optim_step_idx=CRITIC_STEPS - 1) + scoring = original.actor_forward + + expected = sft_batch( + original_ctx, + _sft_pairs(original_ctx, pairs), + microbatch_id=9, + optim_step_idx=CRITIC_STEPS - 1, + grid_index_range=dmd2._score_grid_index_range(original_ctx), + draw="scoring", + ) + for field in ("latents", "timesteps", "timesteps_for_model"): + assert torch.equal(getattr(scoring, field)["visual"], getattr(expected, field)["visual"]) + assert torch.equal(scoring.extras["sigmas"]["visual"], expected.extras["sigmas"]["visual"]) + # Its noise is neither the training forward's nor the reuse mode's at this id. + assert not torch.equal(scoring.latents["visual"], original.actor.latents["visual"]) + assert not torch.equal(scoring.latents["visual"], reuse.actor.latents["visual"]) + assert original.teacher.guidance_scale == reuse.teacher.guidance_scale == 3.0 + for cond in ("pos_cond", "neg_cond", "joint_cond"): + reuse_cond, scoring_cond = getattr(reuse.teacher, cond), getattr(original.teacher, 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_actor_forward_batch(): + ctx = _original_ctx(teacher_guidance_scale=1.0) + ctx.models["transformer"] = _NoisyInputVelocity() + pairs = _pairs(2) + + inputs = [] + [(_, prepared_batches, new_pred, loss)] = _critic_step( + ctx, pairs, CRITIC_STEPS - 1, inputs, teacher=_CondVelocity(2.0) + ) + scores = dmd2.score_last_step_samples(ctx, pairs, inputs) + + assert list(scores) == [100, 101] + scoring = prepared_batches.actor_forward + 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) + 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)) + # The loss is still the SFT loss of the training forward. + sft_loss = sft_loss_formula( + ctx, + pairs, + prepared_batches.actor, + new_pred=new_pred, + old_pred=None, + ref_pred=None, + metrics=_Metrics(), + optim_step_idx=CRITIC_STEPS - 1, + train_output_inputs=[], + ) + assert torch.equal(loss, sft_loss) + + +@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_flow_grpo_streams.py b/tests/fast/backends/fsdp_utils/test_loss_hub_flow_grpo_streams.py index e6eaee5ff..8ba0a3f83 100644 --- a/tests/fast/backends/fsdp_utils/test_loss_hub_flow_grpo_streams.py +++ b/tests/fast/backends/fsdp_utils/test_loss_hub_flow_grpo_streams.py @@ -4,7 +4,7 @@ here are called "wide" and "narrow" (6 and 4 elements per pair) because no model has them. rollout sample ──expand──► pair: per-step fields keyed by stream {"latent": {"wide": x_w, "narrow": x_n}, ...} - │ prepare_flow_grpo_batch: stack each stream across the micro-batch + │ flow_grpo_batch: stack each stream across the micro-batch ▼ PreparedBatch.latents / timesteps / extras[...] every one a {stream: tensor} dict │ flow_grpo_loss_formula @@ -50,8 +50,8 @@ from miles.backends.fsdp_utils.loss_hub.flow_grpo import ( _combine_streams, _stream_weights, + flow_grpo_batch, flow_grpo_loss_formula, - prepare_flow_grpo_batch, ) from miles.backends.fsdp_utils.metrics import new_metric_buffer from miles.backends.fsdp_utils.sde_step_backend import CpsSdeStepBackend, FlowSdeStepBackend @@ -215,7 +215,7 @@ def test_converted_pairs_are_keyed_by_the_primary_stream_and_prepare_reads_them( args = SimpleNamespace(primary_stream="main", rollout_extra_streams=[]) pairs = expand_samples_to_train_pairs(args, [sample], [0.5], [0.5])["train_data"] - prepared = prepare_flow_grpo_batch(_prepare_ctx(), pairs, microbatch_id=0, optim_step_idx=0) + prepared = flow_grpo_batch(_prepare_ctx(), pairs, microbatch_id=0, optim_step_idx=0) assert list(prepared.latents) == ["main"] assert torch.equal(prepared.latents["main"], latents[sde_steps]) @@ -312,7 +312,7 @@ def test_prepare_stacks_every_stream_of_the_pairs(rollout): for index in range(BATCH_SIZE) ] - prepared = prepare_flow_grpo_batch(_prepare_ctx(), pairs, microbatch_id=0, optim_step_idx=0) + prepared = flow_grpo_batch(_prepare_ctx(), pairs, microbatch_id=0, optim_step_idx=0) for stream_name, stream in rollout.streams.items(): assert torch.equal(prepared.latents[stream_name], stream.latent) @@ -349,7 +349,7 @@ def test_a_multi_dit_family_routes_by_the_primary_streams_timestep(rollout): "log_prob_old": {stream_name: stream.log_prob_old[0] for stream_name, stream in rollout.streams.items()}, } - prepared = prepare_flow_grpo_batch(ctx, [pair], microbatch_id=0, optim_step_idx=0) + prepared = flow_grpo_batch(ctx, [pair], microbatch_id=0, optim_step_idx=0) assert prepared.component_name == "high_noise" assert prepared.model is ctx.models["high_noise"] diff --git a/tests/fast/backends/fsdp_utils/test_loss_hub_nft.py b/tests/fast/backends/fsdp_utils/test_loss_hub_nft.py index de17751f3..1222042d4 100644 --- a/tests/fast/backends/fsdp_utils/test_loss_hub_nft.py +++ b/tests/fast/backends/fsdp_utils/test_loss_hub_nft.py @@ -24,7 +24,7 @@ from miles.backends.fsdp_utils.configs.qwen_image import QwenImageTrainPipelineConfig from miles.backends.fsdp_utils.configs.train_pipeline_config import TrainPipelineConfig -from miles.backends.fsdp_utils.loss_hub.nft import corrupt, nft_loss_formula, nft_r_from_advantages, prepare_nft_batch +from miles.backends.fsdp_utils.loss_hub.nft import corrupt, nft_batch, nft_loss_formula, nft_r_from_advantages from miles.backends.fsdp_utils.loss_hub.types import DiffusionLossContext from miles.ray.data_conversion_hub.nft import expand_samples_to_train_pairs from miles.utils.hash_utils import stable_hash @@ -273,18 +273,18 @@ def process_sigma_as_timesteps_input(self, sigmas): seen["sigmas"] = sigmas.clone() return sigmas - prepare_nft_batch(self._ctx(_Recording()), self._batch(), microbatch_id=0, optim_step_idx=0) + nft_batch(self._ctx(_Recording()), self._batch(), microbatch_id=0, optim_step_idx=0) assert torch.equal(seen["sigmas"], torch.tensor(self.SIGMAS)) def test_sd3_style_family_gets_sigma_times_num_train_timesteps(self): - prepared = prepare_nft_batch(self._ctx(_Sd3StyleConfig()), self._batch(), microbatch_id=0, optim_step_idx=0) + prepared = nft_batch(self._ctx(_Sd3StyleConfig()), self._batch(), microbatch_id=0, optim_step_idx=0) assert torch.equal(prepared.timesteps["visual"], torch.tensor(self.SIGMAS)) assert torch.equal( prepared.timesteps_for_model["visual"], torch.tensor(self.SIGMAS) * float(_StubConfig.num_train_timesteps) ) def test_qwen_style_family_gets_the_sigma_bit_exactly(self): - prepared = prepare_nft_batch(self._ctx(_QwenStyleConfig()), self._batch(), microbatch_id=0, optim_step_idx=0) + prepared = nft_batch(self._ctx(_QwenStyleConfig()), self._batch(), microbatch_id=0, optim_step_idx=0) # equal, not allclose: the wrong hook would still pass allclose. assert torch.equal(prepared.timesteps_for_model["visual"], torch.tensor(self.SIGMAS)) @@ -356,14 +356,12 @@ def test_each_sample_draws_its_own_permutation(self): def test_corruption_noise_reproduces(self): ctx = TestPrepareNftBatch()._ctx(_Sd3StyleConfig()) batch = TestPrepareNftBatch()._batch() - first = prepare_nft_batch(ctx, batch, microbatch_id=0, optim_step_idx=0) - second = prepare_nft_batch(ctx, batch, microbatch_id=0, optim_step_idx=0) + first = nft_batch(ctx, batch, microbatch_id=0, optim_step_idx=0) + second = nft_batch(ctx, batch, microbatch_id=0, optim_step_idx=0) assert torch.equal(first.latents["visual"], second.latents["visual"]) def test_a_different_microbatch_draws_different_noise(self): harness = TestPrepareNftBatch() - first = prepare_nft_batch(harness._ctx(_Sd3StyleConfig()), harness._batch(), microbatch_id=0, optim_step_idx=0) - second = prepare_nft_batch( - harness._ctx(_Sd3StyleConfig()), harness._batch(), microbatch_id=1, optim_step_idx=0 - ) + first = nft_batch(harness._ctx(_Sd3StyleConfig()), harness._batch(), microbatch_id=0, optim_step_idx=0) + second = nft_batch(harness._ctx(_Sd3StyleConfig()), harness._batch(), microbatch_id=1, optim_step_idx=0) assert not torch.equal(first.latents["visual"], second.latents["visual"]) diff --git a/tests/fast/backends/fsdp_utils/test_loss_hub_sft.py b/tests/fast/backends/fsdp_utils/test_loss_hub_sft.py index fe846b880..e015ca4ac 100644 --- a/tests/fast/backends/fsdp_utils/test_loss_hub_sft.py +++ b/tests/fast/backends/fsdp_utils/test_loss_hub_sft.py @@ -2,7 +2,7 @@ cached pair["latent"]: {"visual": T} (single-stream families) or {"visual": T, "audio": T} (joint) │ - prepare_sft_batch: + sft_batch: grid ──► FlowNoiseSchedule.shifted(--fsdp-flow-shift[name]) select_component(visual grid, microbatch_id), once, rank-aligned ──► DiT component + the visual grid points it serves each stream gets its own seeded generator @@ -43,7 +43,7 @@ import torch import torch.nn as nn -from miles.backends.fsdp_utils.loss_hub.sft import prepare_sft_batch, select_component, sft_loss_formula +from miles.backends.fsdp_utils.loss_hub.sft import select_component, sft_batch, sft_loss_formula from miles.backends.fsdp_utils.loss_hub.types import DiffusionLossContext, FlowNoiseSchedule from miles.utils.hash_utils import stable_hash @@ -130,7 +130,7 @@ def test_corruption_and_target_identity(self): torch.manual_seed(0) ctx = _ctx({"transformer": nn.Identity()}) batch = _batch() - prepared = prepare_sft_batch(ctx, batch, microbatch_id=0, optim_step_idx=0) + prepared = sft_batch(ctx, batch, microbatch_id=0, optim_step_idx=0) x0 = torch.stack([pair["latent"]["visual"] for pair in batch]).float() sigma = (prepared.timesteps["visual"] / NUM_TRAIN_TIMESTEPS).view(-1, 1, 1, 1, 1) @@ -179,11 +179,11 @@ def test_prepare_is_independent_of_global_rng_state(self): torch.manual_seed(0) global_state = torch.get_rng_state() - first = prepare_sft_batch(_ctx({"transformer": nn.Identity()}), batch, microbatch_id=0, optim_step_idx=0) + first = sft_batch(_ctx({"transformer": nn.Identity()}), batch, microbatch_id=0, optim_step_idx=0) assert torch.equal(torch.get_rng_state(), global_state) torch.rand(1000) - second = prepare_sft_batch(_ctx({"transformer": nn.Identity()}), batch, microbatch_id=0, optim_step_idx=0) + second = sft_batch(_ctx({"transformer": nn.Identity()}), batch, microbatch_id=0, optim_step_idx=0) assert torch.equal(first.timesteps["visual"], second.timesteps["visual"]) assert torch.equal(first.latents["visual"], second.latents["visual"]) assert torch.equal(_visual_target(first), _visual_target(second)) @@ -193,7 +193,7 @@ def test_visual_stream_draws_what_the_single_stream_seed_draws(self): # the draws single-stream SFT made before latents were keyed by stream, rebuilt by hand. ctx = _ctx({"transformer": nn.Identity()}) batch = _batch() - prepared = prepare_sft_batch(ctx, batch, microbatch_id=0, optim_step_idx=0) + prepared = sft_batch(ctx, batch, microbatch_id=0, optim_step_idx=0) generator = torch.Generator().manual_seed(stable_hash("sample", 42, 3, 0, 0)) noise_schedule = FlowNoiseSchedule.shifted(FLOW_SHIFT, NUM_TRAIN_TIMESTEPS) @@ -206,19 +206,19 @@ def test_visual_stream_draws_what_the_single_stream_seed_draws(self): def test_samples_within_microbatch_use_different_noise(self): batch = _batch(bsz=4) - prepared = prepare_sft_batch(_ctx({"transformer": nn.Identity()}), batch, microbatch_id=0, optim_step_idx=0) + prepared = sft_batch(_ctx({"transformer": nn.Identity()}), batch, microbatch_id=0, optim_step_idx=0) x0 = torch.stack([pair["latent"]["visual"] for pair in batch]).float() noise = _visual_target(prepared) + x0 assert all(not torch.equal(noise[0], noise[i]) for i in range(1, len(batch))) def test_identity_changes_draws(self): batch = _batch() - base = prepare_sft_batch(_ctx({"transformer": nn.Identity()}), batch, microbatch_id=0, optim_step_idx=0) - other_rollout = prepare_sft_batch( + base = sft_batch(_ctx({"transformer": nn.Identity()}), batch, microbatch_id=0, optim_step_idx=0) + other_rollout = sft_batch( _ctx({"transformer": nn.Identity()}, rollout_id=4), batch, microbatch_id=0, optim_step_idx=0 ) - other_slot = prepare_sft_batch(_ctx({"transformer": nn.Identity()}), batch, microbatch_id=1, optim_step_idx=0) - other_dp_rank = prepare_sft_batch( + other_slot = sft_batch(_ctx({"transformer": nn.Identity()}), batch, microbatch_id=1, optim_step_idx=0) + other_dp_rank = sft_batch( _ctx({"transformer": nn.Identity()}, dp_rank=1), batch, microbatch_id=0, optim_step_idx=0 ) for other in (other_rollout, other_slot, other_dp_rank): @@ -228,8 +228,8 @@ def test_dual_expert_choice_is_rank_aligned(self): models = {"transformer": nn.Identity(), "transformer_2": nn.Identity()} for slot in range(10): # Different DP ranks choose the same expert but use independent sample RNG. - a = prepare_sft_batch(_ctx(models, dp_rank=0), _batch(), microbatch_id=slot, optim_step_idx=0) - b = prepare_sft_batch(_ctx(models, dp_rank=1), _batch(), microbatch_id=slot, optim_step_idx=0) + a = sft_batch(_ctx(models, dp_rank=0), _batch(), microbatch_id=slot, optim_step_idx=0) + b = sft_batch(_ctx(models, dp_rank=1), _batch(), microbatch_id=slot, optim_step_idx=0) assert a.component_name == b.component_name assert not torch.equal(_visual_target(a), _visual_target(b)) @@ -238,9 +238,7 @@ def test_prepare_draws_from_the_flow_shift_grid(self): noise_schedule = FlowNoiseSchedule.shifted(3.0, 4) torch.testing.assert_close(noise_schedule.sigmas, torch.tensor([1.0, 0.9, 0.75, 0.5, 0.0])) torch.testing.assert_close(noise_schedule.timesteps, torch.tensor([4.0, 3.6, 3.0, 2.0])) - prepared = prepare_sft_batch( - _ctx({"transformer": nn.Identity()}), _batch(bsz=16), microbatch_id=0, optim_step_idx=0 - ) + prepared = sft_batch(_ctx({"transformer": nn.Identity()}), _batch(bsz=16), microbatch_id=0, optim_step_idx=0) grid = FlowNoiseSchedule.shifted(FLOW_SHIFT, NUM_TRAIN_TIMESTEPS) assert set(prepared.extras["sigmas"]["visual"].tolist()) <= set(grid.sigmas[:-1].tolist()) assert set(prepared.timesteps["visual"].tolist()) <= set(grid.timesteps.tolist()) @@ -251,7 +249,7 @@ def _loss(self, prediction_offset, metrics, log_loss_sigma_bucket=5): ctx = _ctx({"transformer": nn.Identity()}) ctx.args.log_loss_sigma_bucket = log_loss_sigma_bucket batch = _batch() - prepared = prepare_sft_batch(ctx, batch, microbatch_id=0, optim_step_idx=0) + prepared = sft_batch(ctx, batch, microbatch_id=0, optim_step_idx=0) new_pred = {"visual": _visual_target(prepared) + prediction_offset} return prepared, sft_loss_formula( ctx, @@ -314,7 +312,7 @@ class TestJointStreams: def test_each_stream_draws_from_its_own_flow_shift_grid(self): # --fsdp-flow-shift visual=3,audio=1: each stream's sigmas lie on its own grid, not on the other's. batch = _joint_batch(16) - prepared = prepare_sft_batch( + prepared = sft_batch( _ctx({"transformer": nn.Identity()}, config=_SingleConfig()), batch, microbatch_id=0, optim_step_idx=0 ) assert set(prepared.latents) == {"visual", "audio"} @@ -337,14 +335,14 @@ def test_streams_share_the_grid_index_but_not_the_noise(self): batch = _joint_batch(32) for pair in batch: pair["latent"]["audio"] = pair["latent"]["visual"].clone() - first = prepare_sft_batch(ctx, batch, microbatch_id=0, optim_step_idx=0) + first = sft_batch(ctx, batch, microbatch_id=0, optim_step_idx=0) grids = {name: FlowNoiseSchedule.shifted(FLOW_SHIFTS[name], NUM_TRAIN_TIMESTEPS) for name in FLOW_SHIFTS} idx = torch.searchsorted(-grids["visual"].sigmas.float(), -first.extras["sigmas"]["visual"]) assert torch.equal(first.extras["sigmas"]["audio"], grids["audio"].sigmas.float()[idx]) assert not torch.equal(first.extras["target"]["visual"], first.extras["target"]["audio"]) for pair in batch: pair["latent"]["action"] = torch.ones(10, 7) - second = prepare_sft_batch(ctx, batch, microbatch_id=0, optim_step_idx=0) + second = sft_batch(ctx, batch, microbatch_id=0, optim_step_idx=0) for name in ("visual", "audio"): assert torch.equal(first.extras["target"][name], second.extras["target"][name]) assert torch.equal(first.timesteps[name], second.timesteps[name]) @@ -353,7 +351,7 @@ def test_loss_averages_each_stream_over_its_own_size(self): # visual (96 elements) off by 1, audio (12 elements) off by 2: per pair 1 + 4, not a size-weighted mix. ctx = _ctx({"transformer": nn.Identity()}, config=_SingleConfig()) batch = _joint_batch(2) - prepared = prepare_sft_batch(ctx, batch, microbatch_id=0, optim_step_idx=0) + prepared = sft_batch(ctx, batch, microbatch_id=0, optim_step_idx=0) predictions = { "visual": (prepared.extras["target"]["visual"] + 1.0).requires_grad_(), "audio": (prepared.extras["target"]["audio"] + 2.0).requires_grad_(), @@ -383,7 +381,7 @@ def test_joint_metrics_split_by_stream_and_bucket_by_own_sigma(self): ctx = _ctx({"transformer": nn.Identity()}, config=_SingleConfig()) batch = _joint_batch(2) - prepared = prepare_sft_batch(ctx, batch, microbatch_id=0, optim_step_idx=0) + prepared = sft_batch(ctx, batch, microbatch_id=0, optim_step_idx=0) predictions = { "visual": prepared.extras["target"]["visual"] + 1.0, "audio": prepared.extras["target"]["audio"] + 2.0, @@ -419,7 +417,7 @@ def test_a_stream_the_config_does_not_predict_adds_no_loss(self): # H3 Ref2VA on a silent target: the audio stream is noised and fed to the DiT, but only visual is predicted. ctx = _ctx({"transformer": nn.Identity()}, config=_SingleConfig()) batch = _joint_batch(2) - prepared = prepare_sft_batch(ctx, batch, microbatch_id=0, optim_step_idx=0) + prepared = sft_batch(ctx, batch, microbatch_id=0, optim_step_idx=0) loss = sft_loss_formula( ctx, batch, @@ -438,7 +436,7 @@ def test_a_stream_left_out_of_supervised_streams_adds_no_loss(self): ctx = _ctx({"transformer": nn.Identity()}, config=_SingleConfig()) ctx.args.fsdp_supervised_streams = ["visual"] batch = _joint_batch(2) - prepared = prepare_sft_batch(ctx, batch, microbatch_id=0, optim_step_idx=0) + prepared = sft_batch(ctx, batch, microbatch_id=0, optim_step_idx=0) metrics = _Metrics() loss = sft_loss_formula( ctx, @@ -464,9 +462,7 @@ def test_visual_stream_selects_a_rank_aligned_expert(self): batch = _joint_batch(4) for slot in range(5): contexts = [_ctx(models, dp_rank=rank) for rank in (0, 1)] - first, second = [ - prepare_sft_batch(context, batch, microbatch_id=slot, optim_step_idx=0) for context in contexts - ] + first, second = [sft_batch(context, batch, microbatch_id=slot, optim_step_idx=0) for context in contexts] assert first.component_name == second.component_name for timestep in first.timesteps["visual"]: component = contexts[0].train_pipeline_config.component_for_timestep(float(timestep)) @@ -475,7 +471,7 @@ def test_visual_stream_selects_a_rank_aligned_expert(self): def test_rejects_misshaped_predictions(self): ctx = _ctx({"transformer": nn.Identity()}, config=_SingleConfig()) batch = _joint_batch(1) - prepared = prepare_sft_batch(ctx, batch, microbatch_id=0, optim_step_idx=0) + prepared = sft_batch(ctx, batch, microbatch_id=0, optim_step_idx=0) predictions = dict(prepared.extras["target"]) predictions["audio"] = predictions["audio"][0] with pytest.raises(ValueError, match="prediction shape"): @@ -495,4 +491,4 @@ def test_rejects_different_stream_sets_in_one_microbatch(self): batch = _joint_batch(2) del batch[1]["latent"]["audio"] with pytest.raises(ValueError, match="latent streams"): - prepare_sft_batch(_ctx({"transformer": nn.Identity()}), batch, microbatch_id=0, optim_step_idx=0) + sft_batch(_ctx({"transformer": nn.Identity()}), batch, microbatch_id=0, optim_step_idx=0) diff --git a/tests/fast/backends/fsdp_utils/test_reference_models.py b/tests/fast/backends/fsdp_utils/test_reference_models.py index 765406e78..d21c93cad 100644 --- a/tests/fast/backends/fsdp_utils/test_reference_models.py +++ b/tests/fast/backends/fsdp_utils/test_reference_models.py @@ -25,6 +25,7 @@ import ast import copy +import dataclasses import logging from argparse import Namespace from pathlib import Path @@ -40,7 +41,8 @@ from miles.backends.fsdp_utils import model_loader from miles.backends.fsdp_utils.ema import EMAOptimizer, reshard_model -from miles.backends.fsdp_utils.input_dtype_policy import apply_input_dtype_policy +from miles.backends.fsdp_utils.input_dtype_policy import InputDtypes +from miles.backends.fsdp_utils.loss_hub.types import PreparedBatch, PreparedBatches from miles.backends.fsdp_utils.models.parallel_plan import FSDPParallelPlan @@ -140,7 +142,7 @@ def load_actor_forward_method(reshard_model=reshard_model): namespace = dict( torch=torch, reshard_model=reshard_model, - apply_input_dtype_policy=apply_input_dtype_policy, + PreparedBatches=PreparedBatches, DiffusionLossContext=object, MetricBuffer=object, ) @@ -162,24 +164,40 @@ def make_actor_forward_harness( true_cfg_scale=None, ): observed = {} - prepared = SimpleNamespace( + timesteps = {"visual": torch.ones(inputs.shape[0], device=inputs.device)} + prepared = PreparedBatch( + latents={"visual": inputs}, + timesteps=timesteps, + timesteps_for_model=timesteps, model=models[component], component_name=component, - latents={"visual": inputs}, - timesteps_for_model={"visual": torch.ones(inputs.shape[0], device=inputs.device)}, - pos_cond=None, - neg_cond=None, - joint_cond=None, + guidance_scale=1.0, use_cfg=False, cfg_batching=False, - guidance_scale=1.0, true_cfg_scale=true_cfg_scale, - teacher_guidance_scale=teacher_guidance_scale, + pos_cond=None, + neg_cond=None, + joint_cond=None, + advantage=torch.zeros(inputs.shape[0]), ) + config = TinyPipelineConfig() + # Stages a test adds besides the training forward, by name. + extra_stages = observed["extra_stages"] = {} def prepare(ctx, batch, **kwargs): observed["prepare_kwargs"] = kwargs - return prepared + teacher = extra_stages.get("teacher") + 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 + teacher = dataclasses.replace( + prepared, + use_cfg=use_cfg, + cfg_batching=use_cfg and config.cfg_batching, + guidance_scale=teacher_guidance_scale, + true_cfg_scale=None, + ) + return PreparedBatches(actor=prepared, teacher=teacher, actor_forward=extra_stages.get("actor_forward")) 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} @@ -195,8 +213,9 @@ 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, + _input_dtypes=InputDtypes.resolve(config.input_dtype_policy, torch.float32), loss_hooks=SimpleNamespace(prepare=prepare, formula=loss_formula), ) return harness, observed @@ -602,6 +621,24 @@ def test_an_unguided_teacher_runs_without_cfg(): ) +def test_an_actor_forward_batch_runs_without_grad_before_the_training_forward(): + harness, observed, actor, teacher = _teacher_harness(None) + other_inputs = torch.full((2, 3), 2.0) + other = dataclasses.replace(harness.loss_hooks.prepare(None, []).actor, latents={"visual": other_inputs}) + observed["extra_stages"].update(teacher=other, actor_forward=other) + + _run_forward(harness, reshard_model=lambda model: None).backward() + + # The teacher on its batch, the model on the actor-forward batch, then the training forward. + assert observed["order"] == ["teacher", "actor", "actor"] + 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(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))) + + def test_no_teacher_forward_unless_the_prepare_hook_asks(): harness, observed, _, teacher = _teacher_harness(None) 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 68e4bed7d..8290f489c 100644 --- a/tests/fast/backends/fsdp_utils/test_train_input_hook.py +++ b/tests/fast/backends/fsdp_utils/test_train_input_hook.py @@ -19,6 +19,7 @@ register_cpu_ci(est_time=5, suite="stage-a-cpu", labels=["fsdp"]) import ast +import dataclasses from argparse import Namespace from contextlib import nullcontext from pathlib import Path @@ -44,6 +45,7 @@ def _load_train_core(new_metric_buffer=lambda *args, **kwargs: SimpleNamespace(r ) namespace = dict( Any=Any, + dataclasses=dataclasses, torch=torch, DiffusionLossContext=DiffusionLossContext, build_microbatch_schedule=build_microbatch_schedule, @@ -118,8 +120,10 @@ def train_input(ctx, train_pairs): ) preprocessed = [{"sample_index": index, "score": scores[index]} for index in (1, 2, 4, 5)] - assert seen_by_input == [(ctx, pairs)] - assert (ctx.rollout_id, ctx.external_data) == (3, {"critic": scores}) + [(input_ctx, input_pairs)] = seen_by_input + assert input_pairs == pairs + for stage_ctx in (input_ctx, ctx): + assert (stage_ctx.rollout_id, stage_ctx.external_data) == (3, {"critic": scores}) # Two optimizer steps of two micro-batches each: the id counts on, the step index follows the window. assert forwarded == [ (0, 0, False, [preprocessed[0]]),