Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
66100f7
feat(ray): hand earlier trainer groups' outputs to later groups as ex…
zhihengy Oct 19, 2026
459222d
fix(fsdp): box the train output so the driver's ray.get only waits
zhihengy Nov 9, 2026
2dc3538
fix(ray): hand later trainer groups the output boxes, not the raw refs
zhihengy Nov 10, 2026
a52f72f
feat(fsdp): add a train-input hook that preprocesses train pairs befo…
zhihengy Oct 24, 2026
77dedd4
refactor(fsdp): rename the train-input hook to custom_train_input_pos…
zhihengy Nov 9, 2026
4868030
feat(rollout): stop the rollout at a random step for DMD2 backward si…
zhihengy Oct 19, 2026
6f9884b
feat(dmd2): train a fake-score critic group from the teacher and scor…
zhihengy Oct 19, 2026
f8cb580
feat(dmd2): train the student with the distribution matching gradient…
zhihengy Oct 19, 2026
0c30c25
fix(dmd2): follow the train-input hook rename in the DMD2 defaults
zhihengy Nov 10, 2026
55a681e
perf(ray): sleep each trainer group right after its train
zhihengy Oct 26, 2026
c5644b6
feat(dmd2): add the MiniMax H3 4-step DMD2 recipe with the media and …
zhihengy Oct 26, 2026
7542deb
feat(dmd2): skip the engine's VAE decode of training rollouts when no…
zhihengy Oct 26, 2026
37695a1
build: declare imageio-ffmpeg, which the eval media muxing imports
zhihengy Nov 10, 2026
8328ef8
docs(h3): say the DMD2 recipe downloads the VidProM prompt list from …
zhihengy Nov 11, 2026
0d9f731
docs(dmd2): count the VidProM prompts after dedup
zhihengy Nov 11, 2026
ce6bda5
fix(dmd2): load the FastH3 reference by its Hub id on every node
Rockdu Nov 11, 2026
4ed4e78
refactor(args): drop the teacher consumer check
Rockdu Nov 10, 2026
b745e50
refactor(fsdp): select loss hooks from a (loss_type, role) table
Rockdu Nov 10, 2026
972e01e
fix(args): reject --custom-*-path outside --loss-type custom_loss
Rockdu Nov 10, 2026
711dc3a
fix(args): reject --diffusion-recompute-old-log-prob under dmd2
Rockdu Nov 10, 2026
0861d2d
refactor(fsdp): pass the loop counters to the hooks as arguments
Rockdu Nov 10, 2026
f7c5597
refactor(fsdp): hand the train-output list to the hooks as an argument
Rockdu Nov 10, 2026
60acc02
refactor(fsdp): freeze DiffusionLossContext
Rockdu Nov 10, 2026
827b527
refactor(fsdp): run the DMD2 teacher forward in the actor, requested …
zhihengy Nov 11, 2026
44eb2b6
fix(fsdp): run the teacher forward without the student's true_cfg_scale
zhihengy Nov 11, 2026
b9e206a
refactor(dmd2): pull the teacher request out of prepare_critic_batch
Rockdu Nov 11, 2026
5e28407
Merge main into dmd2/08-teacher-in-trunk after the PRs below it landed
Rockdu Nov 11, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions docs/fsdp_model_roles.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,9 @@ access `ctx.reference_models` by component name.

A third source, the teacher (`--teacher-load`, with `--teacher-lora-adapter-path` for its
adapters), is loaded by `--loss-type dmd2`, without adapters, into its critic group, which
scores the student's samples with it. Otherwise only a custom hook reads it, from `ctx.teacher_models`,
and teacher inference should run inside `torch.no_grad()`.
scores the student's samples with it. The actor runs it like the reference: on a micro-batch whose
prepare hook sets `PreparedBatch.teacher_guidance_scale`, the teacher's no-grad forward at that CFG
scale runs before the training forward, and the loss formula receives it as `teacher_pred`.

Each source may load pretrained PEFT LoRA adapters, one plain PEFT directory (what
`save_pretrained` writes) per `--update-weight-target-module` entry, in the same order:
Expand Down
2 changes: 1 addition & 1 deletion docs/user-guide/cli-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,7 @@ See [Dtype Control](../advanced/dtype-control.md).
| `--ref-load` | str | – | HF pipeline checkpoint of an independent frozen reference model. Requires `--ref-mode ref`. |
| `--ref-lora-adapter-path` | str+ | – | PEFT adapter directories applied to `--ref-load`, one per `--update-weight-target-module` entry, in order. |
| `--ref-cpu-offload` | flag | off | Keep the reference shards in pinned CPU memory between forwards (FSDP `CPUOffloadPolicy`). |
| `--teacher-load` | str | – | HF pipeline checkpoint of a frozen teacher model, offered to the hooks as `ctx.teacher_models`; `--loss-type dmd2` scores the student's samples with it. |
| `--teacher-load` | str | – | HF pipeline checkpoint of a frozen teacher model; the actor runs it without grad on the micro-batches whose prepare hook sets `PreparedBatch.teacher_guidance_scale`, and `--loss-type dmd2` scores the student's samples with it. |
| `--teacher-lora-adapter-path` | str+ | – | PEFT adapter directories applied to `--teacher-load`, one per `--update-weight-target-module` entry, in order. |
| `--teacher-cpu-offload` | flag | off | Keep the teacher shards in pinned CPU memory between forwards. |
| `--custom-prepare-train-batch-path` | str | – | `custom_loss` only: builds DiT inputs. |
Expand Down
17 changes: 11 additions & 6 deletions docs/user-guide/customization.md
Original file line number Diff line number Diff line change
Expand Up @@ -248,9 +248,9 @@ flags (`--custom-prepare-train-batch-path`, `--custom-loss-function-path`,
falls back to the Flow-GRPO built-in. `dmd2` also trains
a `critic` group before the actor on each rollout: it starts from `--critic-load` (default
`--teacher-load`), learns the student's samples with the SFT loss at `--critic-lr` (default `--lr`).
On its last step it keeps its own x0 predictions from that step's forward, before the update, and
after training its train-output hook hands them with the teacher's x0 at the same noisy inputs to the
actor as `ctx.external_data["critic"]`. The actor trains on those samples only (its train-input hook):
On its last step its prepare hook also asks for the teacher at the same noisy inputs, and its loss
formula keeps the critic's x0 from that step's forward, before the update, next to the teacher's; after
training its train-output hook hands them to the actor as `ctx.external_data["critic"]`. The actor trains on those samples only (its train-input hook):
it recomputes the student's x0 at the rollout's step and moves it along their difference.

DiT forward always stays in the FSDP actor; the loss hook only computes the
Expand Down Expand Up @@ -289,13 +289,16 @@ counts from 0; the old-log-prob recompute of windows 1.. passes their training f
`optim_step_idx` is its optimizer step; the built-in hooks seed their noise from `microbatch_id`.
`PreparedBatch.latents`, `timesteps` and
`timesteps_for_model` are keyed by latent stream name: `"visual"`, plus e.g.
`"audio"` for joint audio-video models.
`"audio"` for joint audio-video models. `PreparedBatch.teacher_guidance_scale` asks the trunk to run the frozen
teacher (`--teacher-load`) without grad on this micro-batch at that CFG scale, over `neg_cond` / `joint_cond`, before
the training forward; the formula receives it as `teacher_pred`.

### `--custom-loss-function-path`

```python
def loss_formula(
ctx, batch, prepared, *, new_pred, old_pred, ref_pred, metrics, optim_step_idx, train_output_inputs, **kwargs
ctx, batch, prepared, *, new_pred, old_pred, ref_pred, teacher_pred, metrics, optim_step_idx,
train_output_inputs, **kwargs
):
...
```
Expand All @@ -304,7 +307,9 @@ Read only under `--loss-type custom_loss`. `optim_step_idx` is the micro-batch's
`train_output_inputs` is the list the formula may fill for the train-output hook, empty at the start of each train
call. `new_pred`, `old_pred` and `ref_pred` are keyed by the same stream
names as `prepared.latents`. `old_pred` (the EMA forward) is `None` for a custom formula, since the trunk runs it
only under `--loss-type nft`; `ref_pred` is `None` with `--ref-mode none`.
only under `--loss-type nft`; `ref_pred` is `None` with `--ref-mode none`. `teacher_pred` is the frozen teacher's
no-grad prediction at `prepared.teacher_guidance_scale`, which the trunk runs before the training forward when the
prepare hook sets that scale, else `None`.

### `--custom-train-input-postprocess-path`

Expand Down
37 changes: 31 additions & 6 deletions miles/backends/fsdp_utils/actor.py
Original file line number Diff line number Diff line change
Expand Up @@ -358,7 +358,6 @@ def _train_core(self, rollout_id: int, rollout_data, external_data: dict[str, An
loss_ctx = DiffusionLossContext(
models=self.models,
reference_models=self.reference_models,
teacher_models=self.teacher_models,
train_pipeline_config=self.train_pipeline_config,
sde_backend=self.sde_backend,
args=self.args,
Expand Down Expand Up @@ -538,7 +537,14 @@ def _forward_train_pair_batch(
default_dtype=forward_dtype,
)

def _compute_noise_pred(model) -> dict[str, torch.Tensor]:
def _compute_noise_pred(
model,
*,
use_cfg: bool = prepared.use_cfg,
cfg_batching: bool = prepared.cfg_batching,
guidance_scale: float = prepared.guidance_scale,
true_cfg_scale: float | None = prepared.true_cfg_scale,
) -> dict[str, torch.Tensor]:
with torch.autocast(
"cuda",
dtype=forward_dtype,
Expand All @@ -551,12 +557,30 @@ def _compute_noise_pred(model) -> dict[str, torch.Tensor]:
pos_cond=pos_cond_in,
neg_cond=neg_cond_in,
joint_cond=joint_cond_in,
use_cfg=prepared.use_cfg,
cfg_batching=prepared.cfg_batching,
guidance_scale=prepared.guidance_scale,
true_cfg_scale=prepared.true_cfg_scale,
use_cfg=use_cfg,
cfg_batching=cfg_batching,
guidance_scale=guidance_scale,
true_cfg_scale=true_cfg_scale,
)

# The frozen teacher runs before the training forward, so its gather never overlaps the activations.
teacher_pred = None
if prepared.teacher_guidance_scale is not None:
if prepared.component_name not in self.teacher_models:
raise ValueError("the prepared batch asks for a teacher forward, which needs --teacher-load")
teacher = self.teacher_models[prepared.component_name]
use_cfg = prepared.teacher_guidance_scale > 1.0
with torch.no_grad():
teacher_pred = _compute_noise_pred(
teacher,
use_cfg=use_cfg,
cfg_batching=use_cfg and train_pipeline_config.cfg_batching,
guidance_scale=prepared.teacher_guidance_scale,
true_cfg_scale=None,
)
# A no-grad forward leaves FSDP's root parameters gathered; sleep must move the shards.
reshard_model(teacher)

new_pred = _compute_noise_pred(prepared.model)

# pi_old: the latest EMA, also when an async batch was sampled with the EMA before it.
Expand All @@ -583,6 +607,7 @@ def _compute_noise_pred(model) -> dict[str, torch.Tensor]:
new_pred=new_pred,
old_pred=old_pred,
ref_pred=ref_pred,
teacher_pred=teacher_pred,
metrics=metrics,
optim_step_idx=optim_step_idx,
train_output_inputs=train_output_inputs,
Expand Down
144 changes: 55 additions & 89 deletions miles/backends/fsdp_utils/loss_hub/dmd2.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@

import torch

from miles.backends.fsdp_utils.ema import reshard_model
from miles.backends.fsdp_utils.input_dtype_policy import apply_input_dtype_policy
from miles.backends.fsdp_utils.loss_hub.sft import prepare_sft_batch, sft_loss_formula
from miles.backends.fsdp_utils.loss_hub.types import DiffusionLossContext, PreparedBatch
from miles.backends.fsdp_utils.metrics import record_rollout_train_abs_diff, step_metric_key
Expand All @@ -24,30 +22,61 @@ def prepare_critic_batch(
) -> PreparedBatch:
"""SFT flow matching on the student's x0 predictions, conditioned on their rollout prompts.

The last step's samples are scored at their noisy inputs, so its grid points come from the scoring range.
The last step's samples are scored at their noisy inputs, so its grid points come from the scoring range and
the teacher runs on them too.
"""
scoring = _is_scoring_step(ctx, optim_step_idx)
prepared = prepare_sft_batch(
ctx,
_sft_batch(ctx, batch),
microbatch_id=microbatch_id,
optim_step_idx=optim_step_idx,
pad_to_len=pad_to_len,
grid_index_range=_score_grid_index_range(ctx) if scoring else None,
)
return _request_teacher_forward(ctx, batch, prepared, pad_to_len=pad_to_len) if scoring else prepared


def _sft_batch(ctx: DiffusionLossContext, batch: list[dict]) -> list[dict]:
config = ctx.train_pipeline_config
sft_batch = [
return [
{
"latent": {"visual": pair["x0"]},
"cond_kwargs": config.prepare_cond_kwargs(pair["denoising_env"].pos_cond_kwargs, ctx.device),
}
for pair in batch
]
grid_index_range = None
if _is_scoring_step(ctx, optim_step_idx):
min_sigma, max_sigma = ctx.args.dmd2_score_sigma_range
num_train_timesteps = config.num_train_timesteps
# Grid index i carries the unshifted sigma 1 - i / num_train_timesteps.
grid_index_range = (round(num_train_timesteps * (1 - max_sigma)), round(num_train_timesteps * (1 - min_sigma)))
return prepare_sft_batch(
ctx,
sft_batch,
microbatch_id=microbatch_id,
optim_step_idx=optim_step_idx,
pad_to_len=pad_to_len,
grid_index_range=grid_index_range,
)


def _score_grid_index_range(ctx: DiffusionLossContext) -> tuple[int, int]:
min_sigma, max_sigma = ctx.args.dmd2_score_sigma_range
num_train_timesteps = ctx.train_pipeline_config.num_train_timesteps
# Grid index i carries the unshifted sigma 1 - i / num_train_timesteps.
return round(num_train_timesteps * (1 - max_sigma)), round(num_train_timesteps * (1 - min_sigma))


def _request_teacher_forward(
ctx: DiffusionLossContext, batch: list[dict], prepared: PreparedBatch, *, pad_to_len: int | None
) -> PreparedBatch:
"""Ask the trunk for the teacher at --dmd2-teacher-guidance-scale on this batch, with the rollout's negative
cond collated for its CFG when the scale needs one."""
config = ctx.train_pipeline_config
guidance_scale = ctx.args.dmd2_teacher_guidance_scale
if guidance_scale <= 1.0:
return dataclasses.replace(prepared, teacher_guidance_scale=guidance_scale)
envs = [pair["denoising_env"] for pair in batch]
if any(env.neg_cond_kwargs is None for env in envs):
raise ValueError(
"--dmd2-teacher-guidance-scale > 1 needs the rollout's negative cond, "
"which the engine returns only for requests that run CFG"
)
pos_list = [config.prepare_cond_kwargs(env.pos_cond_kwargs, ctx.device) for env in envs]
neg_list = [config.prepare_cond_kwargs(env.neg_cond_kwargs, ctx.device) for env in envs]
if config.cfg_batching:
joint_cond = config.collate_cond_for_sample_batch(pos_list + neg_list, ctx.device, pad_to_len=pad_to_len)
return dataclasses.replace(prepared, joint_cond=joint_cond, teacher_guidance_scale=guidance_scale)
neg_cond = config.collate_cond_for_sample_batch(neg_list, ctx.device, pad_to_len=pad_to_len)
return dataclasses.replace(prepared, neg_cond=neg_cond, teacher_guidance_scale=guidance_scale)


def critic_loss_formula(
Expand All @@ -58,6 +87,7 @@ def critic_loss_formula(
new_pred: dict[str, torch.Tensor],
old_pred: dict[str, torch.Tensor] | None,
ref_pred: dict[str, torch.Tensor] | None,
teacher_pred: dict[str, torch.Tensor] | None = None,
metrics: MetricBuffer,
optim_step_idx: int,
train_output_inputs: list,
Expand All @@ -66,15 +96,15 @@ def critic_loss_formula(
) -> torch.Tensor:
"""The SFT loss in --dmd2-critic-loss-space.

On the last step it also keeps the critic's x0 at each noisy input, before that step's update.
On the last step it also keeps the critic's and the teacher's x0 at each noisy input, before that step's update.
"""
latents = prepared.latents["visual"]
sigmas = prepared.extras["sigmas"]["visual"].view(len(batch), *([1] * (latents.ndim - 1)))
if _is_scoring_step(ctx, optim_step_idx):
x0_fake = latents - sigmas * new_pred["visual"].detach().float()
train_output_inputs.append(
(batch, prepared.component_name, latents, prepared.timesteps["visual"], sigmas, x0_fake)
)
x0_real = latents - sigmas * teacher_pred["visual"].float()
for pair, real, fake in zip(batch, x0_real, x0_fake, strict=True):
train_output_inputs.append((pair["sample_index"], real, fake))
if ctx.args.dmd2_critic_loss_space == "x0":
# x0 = x_sigma - sigma v, so the MSE on x0 weights the velocity MSE by sigma^2.
x0_target = latents - sigmas * prepared.extras["target"]["visual"]
Expand All @@ -98,79 +128,14 @@ def critic_loss_formula(
def score_last_step_samples(
ctx: DiffusionLossContext, train_pairs: list[dict], train_output_inputs: list
) -> dict[int, dict]:
"""The teacher's x0 at each scored sample's noisy input, next to the critic's x0 kept there, by sample."""
predictions = {}
for batch, component_name, latents, timesteps, sigmas, x0_fake in train_output_inputs:
teacher = ctx.teacher_models[component_name]
real_pred = _predict_velocity(ctx, teacher, batch, latents, timesteps, ctx.args.dmd2_teacher_guidance_scale)
for pair, x0_real, fake in zip(batch, latents - sigmas * real_pred, x0_fake, strict=True):
predictions[pair["sample_index"]] = {"x0_real": x0_real.cpu(), "x0_fake": fake.cpu()}

# A no-grad forward leaves FSDP's root parameters gathered; sleep must move the shards.
for model in ctx.teacher_models.values():
reshard_model(model)
return predictions
"""The teacher's and the critic's x0 kept at each scored sample's noisy input, by sample."""
return {index: {"x0_real": real.cpu(), "x0_fake": fake.cpu()} for index, real, fake in train_output_inputs}


def _is_scoring_step(ctx: DiffusionLossContext, optim_step_idx: int) -> bool:
return optim_step_idx == ctx.args.num_steps_per_rollout - 1


def _predict_velocity(
ctx: DiffusionLossContext,
model: torch.nn.Module,
batch: list[dict],
latents: torch.Tensor,
timesteps: torch.Tensor,
guidance_scale: float,
) -> torch.Tensor:
"""One velocity prediction, with CFG over the rollout's negative cond when ``guidance_scale > 1``."""
config = ctx.train_pipeline_config
use_cfg = guidance_scale > 1.0
envs = [pair["denoising_env"] for pair in batch]
if use_cfg and any(env.neg_cond_kwargs is None for env in envs):
raise ValueError(
"--dmd2-teacher-guidance-scale > 1 needs the rollout's negative cond, "
"which the engine returns only for requests that run CFG"
)
pos_list = [config.prepare_cond_kwargs(env.pos_cond_kwargs, ctx.device) for env in envs]
neg_list = [config.prepare_cond_kwargs(env.neg_cond_kwargs, ctx.device) for env in envs] if use_cfg else []
cfg_batching = use_cfg and config.cfg_batching
pos_cond = neg_cond = joint_cond = None
if cfg_batching:
joint_cond = config.collate_cond_for_sample_batch(pos_list + neg_list, ctx.device)
else:
pos_cond = config.collate_cond_for_sample_batch(pos_list, ctx.device)
if use_cfg:
neg_cond = config.collate_cond_for_sample_batch(neg_list, ctx.device)

latents_in, timesteps_in, (pos_in, neg_in, joint_in) = apply_input_dtype_policy(
config.input_dtype_policy,
latents={"visual": latents},
timesteps={"visual": config.process_timestep_as_input(timesteps)},
conds=(pos_cond, neg_cond, joint_cond),
default_dtype=ctx.forward_dtype,
)
with torch.autocast(
"cuda",
dtype=ctx.forward_dtype,
enabled=ctx.forward_dtype != torch.float32 and config.enable_autocast,
):
pred = config.compute_noise_pred(
model=model,
latents_input=latents_in,
timesteps_input=timesteps_in,
pos_cond=pos_in,
neg_cond=neg_in,
joint_cond=joint_in,
use_cfg=use_cfg,
cfg_batching=cfg_batching,
guidance_scale=guidance_scale,
true_cfg_scale=None,
)
return pred["visual"].float()


def select_scored_pairs(ctx: DiffusionLossContext, train_pairs: list[dict]) -> list[dict]:
"""The pairs of the critic's last step, which it scored; the actor trains on these only."""
scores = ctx.external_data["critic"]
Expand Down Expand Up @@ -231,6 +196,7 @@ def dmd2_loss_formula(
new_pred: dict[str, torch.Tensor],
old_pred: dict[str, torch.Tensor] | None,
ref_pred: dict[str, torch.Tensor] | None,
teacher_pred: dict[str, torch.Tensor] | None = None,
metrics: MetricBuffer,
optim_step_idx: int,
train_output_inputs: list,
Expand Down
1 change: 1 addition & 0 deletions miles/backends/fsdp_utils/loss_hub/flow_grpo.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ def flow_grpo_loss_formula(
new_pred: dict[str, torch.Tensor],
old_pred: dict[str, torch.Tensor] | None,
ref_pred: dict[str, torch.Tensor] | None,
teacher_pred: dict[str, torch.Tensor] | None = None,
metrics: MetricBuffer,
optim_step_idx: int,
train_output_inputs: list,
Expand Down
1 change: 1 addition & 0 deletions miles/backends/fsdp_utils/loss_hub/nft.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ def nft_loss_formula(
new_pred: dict[str, torch.Tensor],
old_pred: dict[str, torch.Tensor] | None,
ref_pred: dict[str, torch.Tensor] | None,
teacher_pred: dict[str, torch.Tensor] | None = None,
metrics: MetricBuffer,
optim_step_idx: int,
train_output_inputs: list,
Expand Down
1 change: 1 addition & 0 deletions miles/backends/fsdp_utils/loss_hub/sft.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ def sft_loss_formula(
new_pred: dict[str, torch.Tensor],
old_pred: dict[str, torch.Tensor] | None,
ref_pred: dict[str, torch.Tensor] | None,
teacher_pred: dict[str, torch.Tensor] | None = None,
metrics: MetricBuffer,
optim_step_idx: int,
train_output_inputs: list,
Expand Down
3 changes: 2 additions & 1 deletion miles/backends/fsdp_utils/loss_hub/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ class DiffusionLossContext:
rollout_id: int = 0
dp_rank: int = 0
reference_models: dict[str, torch.nn.Module] = field(default_factory=dict)
teacher_models: dict[str, torch.nn.Module] = field(default_factory=dict)
external_data: dict[str, Any] = field(default_factory=dict)


Expand Down Expand Up @@ -70,3 +69,5 @@ class PreparedBatch:
joint_cond: dict | None
advantage: torch.Tensor
extras: dict[str, Any] = field(default_factory=dict)
# CFG scale of the frozen teacher's no-grad forward on this batch; None runs no teacher forward.
teacher_guidance_scale: float | None = None
Loading
Loading