Skip to content
Closed
1 change: 1 addition & 0 deletions docs/user-guide/cli-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,7 @@ See [Dtype Control](../advanced/dtype-control.md).
| `--dmd2-teacher-guidance-scale` | float | – | Required by `dmd2`: the teacher's CFG scale when scoring the student's samples; `1` runs it unguided. |
| `--dmd2-score-sigma-range` | float float | `0.02 0.98` | `MIN MAX` of the unshifted sigma at which `dmd2` scores the student's samples: the last critic step draws grid points in this range and reads them through the visual `--fsdp-flow-shift`. The default is the reference DMD2 range. |
| `--dmd2-critic-loss-space` | str | `velocity` | `velocity` or `x0`: the space of the critic's flow-matching loss. `x0` regresses x0 = x_σ − σ·v, which weights the velocity MSE by σ². |
| `--dmd2-critic-scoring` | str | `reuse-critic-step` | How the critic scores its last step's samples. `reuse-critic-step`: that step's training forward, drawn in `--dmd2-score-sigma-range`, is the score. `original`: the reference's separate draw and critic forward before the critic trains on them (one more critic forward per scored sample). |
| `--critic-load` | str | `--teacher-load` | `dmd2` only: HF pipeline checkpoint the critic starts from. Its checkpoints go to the sibling `<--save>_critic` dir. |
| `--critic-lr` | float | `--lr` | `dmd2` only: the critic's learning rate. |

Expand Down
3 changes: 3 additions & 0 deletions docs/user-guide/customization.md
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,9 @@ On its last step its prepare hook also asks for the teacher at the same noisy in
formula keeps the critic's x0 from that step's forward, before the update, next to the teacher's; after
training its train-output hook hands them to the actor as `ctx.external_data["critic"]`. The actor trains on those samples only (its train-input hook):
it recomputes the student's x0 at the rollout's step and moves it along their difference.
Under `--dmd2-critic-scoring original` the last step is plain SFT, and before it trains the trunk runs
the critic's `forward_only` hooks (`prepare_scoring_batch`, `scoring_formula`) without grad on that
step's pairs, at a fresh draw.

DiT forward always stays in the FSDP actor; the loss hook only computes the
objective.
Expand Down
28 changes: 24 additions & 4 deletions miles/backends/fsdp_utils/actor.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
)
from .ema import EMAOptimizer, reshard_model
from .input_dtype_policy import apply_input_dtype_policy
from .loss_hub import DiffusionLossContext, get_loss_hooks
from .loss_hub import DiffusionLossContext, ForwardOnlyHooks, LossHooks, get_loss_hooks
from .lr_scheduler import get_lr_scheduler
from .metrics import new_metric_buffer
from .mixed_precision import parse_dtype_from_str
Expand Down Expand Up @@ -429,6 +429,8 @@ def _train_core(self, rollout_id: int, rollout_data, external_data: dict[str, An
# ------------- Forward / Backward -------------
with timer("actor_train"):
microbatch_id = 0
# past the training ids: no draw shared with a training forward
forward_only_microbatch_id = sum(len(microbatch_ranges) for microbatch_ranges in microbatch_schedule)
for optim_step_idx, microbatch_ranges in enumerate(microbatch_schedule):
self.optimizer.zero_grad(set_to_none=True)

Expand All @@ -447,6 +449,22 @@ def _train_core(self, rollout_id: int, rollout_data, external_data: dict[str, An
num_rollout_steps=self.args.diffusion_num_steps,
)

forward_only = self.loss_hooks.forward_only
if forward_only is not None and forward_only.runs_before_step(loss_ctx, optim_step_idx):
with torch.no_grad():
for pair_lo, pair_hi in microbatch_ranges:
self._forward_train_pair_batch(
loss_ctx,
train_pairs[pair_lo:pair_hi],
microbatch_id=forward_only_microbatch_id,
optim_step_idx=optim_step_idx,
train_output_inputs=train_output_inputs,
metrics=metrics,
pad_to_len=legacy_pad_to_len,
hooks=forward_only,
)
forward_only_microbatch_id += 1

for pair_lo, pair_hi in microbatch_ranges:
chunk = train_pairs[pair_lo:pair_hi]
loss_sum = self._forward_train_pair_batch(
Expand Down Expand Up @@ -519,10 +537,12 @@ def _forward_train_pair_batch(
pad_to_len: int | None = None,
write_old_log_prob: bool = False,
old_log_prob_from_new: bool = False,
hooks: LossHooks | ForwardOnlyHooks | None = None,
) -> torch.Tensor | None:
"""Run one prepared diffusion micro-batch: number ``microbatch_id`` of the rollout, in optimizer step
``optim_step_idx``."""
prepared = self.loss_hooks.prepare(
``optim_step_idx``, through the group's hooks or ``hooks``."""
hooks = self.loss_hooks if hooks is None else hooks
prepared = hooks.prepare(
ctx, batch, microbatch_id=microbatch_id, optim_step_idx=optim_step_idx, pad_to_len=pad_to_len
)
train_pipeline_config = self.train_pipeline_config
Expand Down Expand Up @@ -600,7 +620,7 @@ def _compute_noise_pred(
# PEFT re-enables adapter gradients on exit; reshard first so that lands on the shards, not gathered copies.
reshard_model(prepared.model)

return self.loss_hooks.formula(
return hooks.formula(
ctx,
batch,
prepared,
Expand Down
28 changes: 25 additions & 3 deletions miles/backends/fsdp_utils/loss_hub/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,12 @@
from miles.backends.fsdp_utils.loss_hub.dmd2 import (
critic_loss_formula,
dmd2_loss_formula,
is_scored_before_training,
prepare_critic_batch,
prepare_generator_batch,
prepare_scoring_batch,
score_last_step_samples,
scoring_formula,
select_scored_pairs,
)
from miles.backends.fsdp_utils.loss_hub.flow_grpo import flow_grpo_loss_formula, prepare_flow_grpo_batch
Expand All @@ -23,7 +26,20 @@
from miles.backends.fsdp_utils.loss_hub.types import DiffusionLossContext, PreparedBatch
from miles.utils.misc import load_function

__all__ = ["LOSS_HOOKS", "DiffusionLossContext", "LossHooks", "PreparedBatch", "get_loss_hooks"]
__all__ = ["LOSS_HOOKS", "DiffusionLossContext", "ForwardOnlyHooks", "LossHooks", "PreparedBatch", "get_loss_hooks"]


@dataclass(frozen=True)
class ForwardOnlyHooks:
"""A no-grad pass over an optimizer step's micro-batches, run before the step trains them.

It runs before the steps ``runs_before_step(ctx, optim_step_idx)`` names. ``prepare`` and ``formula`` are called
as a ``LossHooks``' are, with micro-batch ids past the rollout's training ones; the formula returns no loss.
"""

runs_before_step: Callable[[DiffusionLossContext, int], bool]
prepare: Callable[..., PreparedBatch]
formula: Callable[..., None]


@dataclass(frozen=True)
Expand All @@ -35,21 +51,27 @@ class LossHooks:
...)`` turns the predictions into its loss, ``train_input`` preprocesses the rank's train pairs before
micro-batching, and ``train_output(ctx, train_pairs, train_output_inputs)`` runs after the train steps and hands
its return value to the groups that train later; ``train_output_inputs`` is the list the formulas filled during
this train call.
this train call, those of ``forward_only`` included.
"""

prepare: Callable[..., PreparedBatch]
formula: Callable[..., torch.Tensor | None]
train_input: Callable[[DiffusionLossContext, list], list] | None = None
train_output: Callable[[DiffusionLossContext, list, list], Any] | None = None
forward_only: ForwardOnlyHooks | None = None


LOSS_HOOKS: dict[tuple[str, str], LossHooks] = {
("policy_loss", "actor"): LossHooks(prepare_flow_grpo_batch, flow_grpo_loss_formula),
("nft", "actor"): LossHooks(prepare_nft_batch, nft_loss_formula),
("sft_loss", "actor"): LossHooks(prepare_sft_batch, sft_loss_formula),
("dmd2", "actor"): LossHooks(prepare_generator_batch, dmd2_loss_formula, train_input=select_scored_pairs),
("dmd2", "critic"): LossHooks(prepare_critic_batch, critic_loss_formula, train_output=score_last_step_samples),
("dmd2", "critic"): LossHooks(
prepare_critic_batch,
critic_loss_formula,
train_output=score_last_step_samples,
forward_only=ForwardOnlyHooks(is_scored_before_training, prepare_scoring_batch, scoring_formula),
),
}


Expand Down
91 changes: 78 additions & 13 deletions miles/backends/fsdp_utils/loss_hub/dmd2.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
"""DMD2 hooks: the critic group learns and scores the student's samples; the actor follows the scores."""
"""DMD2 hooks: the critic group learns and scores the student's samples; the actor follows the scores.

--dmd2-critic-scoring picks how the critic scores its last step's samples: ``reuse-critic-step`` scores them with
that step's training forward (the critic hooks' last step is the scoring batch), ``original`` scores them with a
separate forward-only pass (the critic's ``forward_only`` hooks) before the critic trains that step on them, as
tianweiy/DMD2 does.
"""

from __future__ import annotations

Expand All @@ -22,19 +28,37 @@ def prepare_critic_batch(
) -> PreparedBatch:
"""SFT flow matching on the student's x0 predictions, conditioned on their rollout prompts.

The last step's samples are scored at their noisy inputs, so its grid points come from the scoring range and
the teacher runs on them too.
Under --dmd2-critic-scoring reuse-critic-step the last step's samples are scored at their noisy inputs, so that
step prepares the scoring batch: grid points from the scoring range, the teacher asked for.
"""
scoring = _is_scoring_step(ctx, optim_step_idx)
if _is_scoring_step(ctx, optim_step_idx):
return prepare_scoring_batch(
ctx, batch, microbatch_id=microbatch_id, optim_step_idx=optim_step_idx, pad_to_len=pad_to_len
)
return prepare_sft_batch(
ctx, _sft_batch(ctx, batch), microbatch_id=microbatch_id, optim_step_idx=optim_step_idx, pad_to_len=pad_to_len
)


def prepare_scoring_batch(
ctx: DiffusionLossContext,
batch: list[dict],
*,
microbatch_id: int,
optim_step_idx: int,
pad_to_len: int | None = None,
) -> PreparedBatch:
"""The critic's SFT draw on the student's x0 at grid points in --dmd2-score-sigma-range, with the teacher asked
for at the same noisy inputs."""
prepared = prepare_sft_batch(
ctx,
_sft_batch(ctx, batch),
microbatch_id=microbatch_id,
optim_step_idx=optim_step_idx,
pad_to_len=pad_to_len,
grid_index_range=_score_grid_index_range(ctx) if scoring else None,
grid_index_range=_score_grid_index_range(ctx),
)
return _request_teacher_forward(ctx, batch, prepared, pad_to_len=pad_to_len) if scoring else prepared
return _request_teacher_forward(ctx, batch, prepared, pad_to_len=pad_to_len)


def _sft_batch(ctx: DiffusionLossContext, batch: list[dict]) -> list[dict]:
Expand Down Expand Up @@ -98,14 +122,11 @@ def critic_loss_formula(

On the last step it also keeps the critic's and the teacher's x0 at each noisy input, before that step's update.
"""
latents = prepared.latents["visual"]
sigmas = prepared.extras["sigmas"]["visual"].view(len(batch), *([1] * (latents.ndim - 1)))
if _is_scoring_step(ctx, optim_step_idx):
x0_fake = latents - sigmas * new_pred["visual"].detach().float()
x0_real = latents - sigmas * teacher_pred["visual"].float()
for pair, real, fake in zip(batch, x0_real, x0_fake, strict=True):
train_output_inputs.append((pair["sample_index"], real, fake))
keep_scores(batch, prepared, new_pred, teacher_pred, train_output_inputs)
if ctx.args.dmd2_critic_loss_space == "x0":
latents = prepared.latents["visual"]
sigmas = prepared.extras["sigmas"]["visual"].view(len(batch), *([1] * (latents.ndim - 1)))
# x0 = x_sigma - sigma v, so the MSE on x0 weights the velocity MSE by sigma^2.
x0_target = latents - sigmas * prepared.extras["target"]["visual"]
prepared = dataclasses.replace(prepared, extras={**prepared.extras, "target": {"visual": x0_target}})
Expand All @@ -125,6 +146,44 @@ def critic_loss_formula(
)


def scoring_formula(
ctx: DiffusionLossContext,
batch: list[dict],
prepared: PreparedBatch,
*,
new_pred: dict[str, torch.Tensor],
old_pred: dict[str, torch.Tensor] | None,
ref_pred: dict[str, torch.Tensor] | None,
teacher_pred: dict[str, torch.Tensor] | None = None,
metrics: MetricBuffer,
optim_step_idx: int,
train_output_inputs: list,
**kwargs,
) -> None:
"""Keeps the critic's and the teacher's x0 at each noisy input and computes no loss.

The forward-only scoring of --dmd2-critic-scoring original, before the critic trains its last step on these samples.
"""
keep_scores(batch, prepared, new_pred, teacher_pred, train_output_inputs)
return None


def keep_scores(
batch: list[dict],
prepared: PreparedBatch,
new_pred: dict[str, torch.Tensor],
teacher_pred: dict[str, torch.Tensor] | None,
train_output_inputs: list,
) -> None:
"""Per sample, x0_fake = x_s - sigma v_critic and x0_real = x_s - sigma v_teacher, for score_last_step_samples."""
latents = prepared.latents["visual"]
sigmas = prepared.extras["sigmas"]["visual"].view(len(batch), *([1] * (latents.ndim - 1)))
x0_fake = latents - sigmas * new_pred["visual"].detach().float()
x0_real = latents - sigmas * teacher_pred["visual"].float()
for pair, real, fake in zip(batch, x0_real, x0_fake, strict=True):
train_output_inputs.append((pair["sample_index"], real, fake))


def score_last_step_samples(
ctx: DiffusionLossContext, train_pairs: list[dict], train_output_inputs: list
) -> dict[int, dict]:
Expand All @@ -133,7 +192,13 @@ def score_last_step_samples(


def _is_scoring_step(ctx: DiffusionLossContext, optim_step_idx: int) -> bool:
return optim_step_idx == ctx.args.num_steps_per_rollout - 1
"""Under reuse-critic-step the last step's training forward is the critic's score; under original no step is."""
return ctx.args.dmd2_critic_scoring == "reuse-critic-step" and optim_step_idx == ctx.args.num_steps_per_rollout - 1


def is_scored_before_training(ctx: DiffusionLossContext, optim_step_idx: int) -> bool:
"""Under original the last step's samples are scored forward-only, before the critic trains that step."""
return ctx.args.dmd2_critic_scoring == "original" and optim_step_idx == ctx.args.num_steps_per_rollout - 1


def select_scored_pairs(ctx: DiffusionLossContext, train_pairs: list[dict]) -> list[dict]:
Expand Down
10 changes: 10 additions & 0 deletions miles/utils/arguments.py
Original file line number Diff line number Diff line change
Expand Up @@ -1061,6 +1061,16 @@ def add_algo_arguments(parser):
help="Space of the DMD2 critic's flow-matching loss: velocity, or x0 = x_sigma - sigma * v, "
"which weights the velocity MSE by sigma^2.",
)
parser.add_argument(
"--dmd2-critic-scoring",
type=str,
choices=["reuse-critic-step", "original"],
default="reuse-critic-step",
help="How the DMD2 critic scores its last step's samples. reuse-critic-step: that step's training "
"forward, drawn in --dmd2-score-sigma-range, is the critic's score, so only the teacher's forward "
"is added. original: tianweiy/DMD2's order, a separate draw and critic forward on those samples "
"before the critic trains on them, which costs a critic forward per scored sample.",
)
parser.add_argument(
"--critic-load",
type=str,
Expand Down
Loading
Loading