Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 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
5abb25e
Merge main into dmd2/refactor-a-hook-registry after #330-#343 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
2 changes: 1 addition & 1 deletion docs/advanced/sde-backend.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ Implementation: `miles/backends/fsdp_utils/sde_step_backend.py`. Override with
|---|---|---|---|
| Flow-SDE | `sde` (default) | `FlowSdeStepBackend` | Transition noise std η·√(σ/(1−σ))·√(−dt) with the rollout's recorded σ (the grid's second σ replaces the denominator's σ at σ = 1); [Flow-GRPO](https://arxiv.org/abs/2505.05470) |
| CPS | `cps` | `CpsSdeStepBackend` | Transition noise std σ_next·sin(η·π/2); log-prob is −(x−μ)², without the Gaussian constants or the 1/(2σ²) scale (forces `--diffusion-log-prob-no-const`); [FlowCPS](https://arxiv.org/abs/2509.05952) |
| ODE | `ode` | `FlowSdeStepBackend` (placeholder; NFT never calls it) | Deterministic; NFT (or a custom loss formula) only — with the Flow-GRPO loss it is rejected at parse time |
| ODE | `ode` | `FlowSdeStepBackend` (placeholder; NFT and DMD2 never call it) | Deterministic; NFT, DMD2 or a custom loss formula only — with the Flow-GRPO loss it is rejected at parse time |

`--diffusion-noise-level` (η) sets the SDE noise scale. DanceGRPO-style constant-η
schedules use the same `sde` backend with a tuned η
Expand Down
2 changes: 1 addition & 1 deletion docs/developer/contributor-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ miles_diffusion/
│ │ │ ├── actor.py # FSDPTrainRayActor: wrap, forward, loss, step
│ │ │ ├── configs/ # TrainPipelineConfig per model family
│ │ │ ├── models/ # native model packages (ltx) + diffusers parallel plans
│ │ │ ├── loss_hub/ # flow_grpo / nft / sft objectives
│ │ │ ├── loss_hub/ # loss hooks per (loss_type, role): flow_grpo / nft / sft / dmd2
│ │ │ ├── sequence_parallel/ # USP = Ulysses × Ring
│ │ │ ├── monkey_patches/ # FSDP2 param-dtype patch (torch 2.11 gated)
│ │ │ ├── mixed_precision.py # per-parameter dtype map compilation
Expand Down
5 changes: 2 additions & 3 deletions docs/fsdp_model_roles.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,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. Otherwise it has no built-in consumer: `--teacher-load`
requires a custom prepare/loss/train-output hook, which reads it from `ctx.teacher_models`, and
teacher inference should run inside `torch.no_grad()`.
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()`.

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
12 changes: 6 additions & 6 deletions docs/user-guide/cli-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ See [Dtype Control](../advanced/dtype-control.md).

| Flag | Default | What |
|---|---|---|
| `--loss-type` | `policy_loss` | `policy_loss` (Flow-GRPO), `nft`, `sft_loss`, `custom_loss`, `dmd2`. |
| `--loss-type` | `policy_loss` | `policy_loss` (Flow-GRPO), `nft`, `sft_loss`, `custom_loss`, `dmd2`; selects each trainer group's hooks from the loss hub, only `custom_loss` reads the four `--custom-*-path` hook flags. |
| `--advantage-estimator` | `grpo` | Only `grpo` today. |
| `--diffusion-clip-range` | `1e-4` | PPO ratio clip. |
| `--diffusion-adv-clip-max` | `5.0` | Advantage clamp. |
Expand Down Expand Up @@ -274,13 +274,13 @@ 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, read only by custom prepare/loss/train-output hooks as `ctx.teacher_models`, so it requires `--custom-prepare-train-batch-path`, `--custom-loss-function-path` or `--custom-train-output-function-path`. |
| `--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-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 | – | Builds DiT inputs. |
| `--custom-loss-function-path` | str | – | Loss **formula** only — the DiT forward stays in the actor. |
| `--custom-train-input-postprocess-path` | str | – | Preprocesses a rank's train pairs (the converted rollout output) before they are split into micro-batches, and returns the pairs to train on. `ctx.external_data` holds earlier trainer groups' outputs. |
| `--custom-train-output-function-path` | str | – | Runs without grad after a rollout's train steps; its return value reaches the paired rank of each later trainer group as `ctx.external_data[<role>]`. |
| `--custom-prepare-train-batch-path` | str | – | `custom_loss` only: builds DiT inputs. |
| `--custom-loss-function-path` | str | – | `custom_loss` only: loss **formula** only — the DiT forward stays in the actor. |
| `--custom-train-input-postprocess-path` | str | – | `custom_loss` only: preprocesses a rank's train pairs (the converted rollout output) before they are split into micro-batches, and returns the pairs to train on. `ctx.external_data` holds earlier trainer groups' outputs. |
| `--custom-train-output-function-path` | str | – | `custom_loss` only: runs without grad after a rollout's train steps; its return value reaches the paired rank of each later trainer group as `ctx.external_data[<role>]`. |
| `--diffusion-nft-beta` | float | `1.0` | |
| `--diffusion-nft-timestep-strategy-path` | str | `…nft.drop_random_steps` | `(args, num_steps, generator) -> list[int]` returning the denoising steps each sample trains on, in training order; `generator` is seeded per sample. Built in: `drop_random_steps` (random order), `drop_final_steps` (schedule order, noisiest first). The final clean output (σ = 0) is never a training step. |
| `--diffusion-nft-num-dropped-timesteps` | int | `0` | Steps the built-in strategies drop: random ones per sample for `drop_random_steps`, the final (lowest-noise) ones for `drop_final_steps`. |
Expand Down
68 changes: 38 additions & 30 deletions docs/user-guide/customization.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ signatures they expect, and the defaults they replace — in the same spirit as
| **Model family** | `--train-pipeline-config-path` | Family `TrainPipelineConfig` |
| | `--model-backend-path` | Model load / FSDP backend |

`--loss-type` (`policy_loss` / `nft` / `sft_loss` / `custom_loss` / `dmd2`) is the
shortcut that auto-fills several of the train-side paths; see § Training.
`--loss-type` (`policy_loss` / `nft` / `sft_loss` / `custom_loss` / `dmd2`) selects the train-side
hooks of each trainer group from the loss hub, and picks the default expand path; see § Training.

***

Expand Down Expand Up @@ -226,27 +226,32 @@ def buffer_filter(

## Training

`--loss-type` picks the default prepare / formula / expand paths:

| `--loss-type` | Expand pairs | Prepare | Loss formula |
|---|---|---|---|
| `policy_loss` (default) | Flow-GRPO built-in | `prepare_flow_grpo_batch` | `flow_grpo_loss_formula` |
| `nft` | `data_conversion_hub.nft.expand_samples_to_train_pairs` | `loss_hub.nft.prepare_nft_batch` | `nft_loss_formula` |
| `sft_loss` | none; convert `sft_rollout.convert_samples_to_train_data` | `loss_hub.sft.prepare_sft_batch` | `sft_loss_formula` |
| `custom_loss` | your expand (or convert) | your prepare | your formula |
| `dmd2` | `data_conversion_hub.dmd2.expand_samples_to_train_pairs` | `loss_hub.dmd2.prepare_generator_batch` | `dmd2_loss_formula` |

`sft_loss` auto-fills nothing: it requires the convert, rollout-log, prepare and loss
paths, plus `--train-only` and a rollout function that runs no engines (e.g.
`miles.rollout.sft_rollout.generate_rollout`; see `scripts/run_diffusion_sft_wan22.py`). `custom_loss` behaves like `policy_loss`:
any hook left unset 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 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 defaults to
`loss_hub.dmd2.select_scored_pairs`): it recomputes the student's x0 at the rollout's step and moves
it along their difference.
`--loss-type` picks the default expand path and selects each trainer group's hooks from the loss hub,
`miles.backends.fsdp_utils.loss_hub.LOSS_HOOKS`, keyed by `(loss_type, role)`. A group's hooks are
its prepare, its loss formula (the function `--custom-loss-function-path` names under `custom_loss`),
and optionally a train-input and a train-output hook:

| `--loss-type` | Expand pairs | Prepare | Loss formula | Train-input / train-output |
|---|---|---|---|---|
| `policy_loss` (default) | Flow-GRPO built-in | `prepare_flow_grpo_batch` | `flow_grpo_loss_formula` | – |
| `nft` | `data_conversion_hub.nft.expand_samples_to_train_pairs` | `loss_hub.nft.prepare_nft_batch` | `nft_loss_formula` | – |
| `sft_loss` | none; convert `sft_rollout.convert_samples_to_train_data` | `loss_hub.sft.prepare_sft_batch` | `sft_loss_formula` | – |
| `custom_loss` | your expand (or convert) | your prepare | your formula | yours |
| `dmd2`, actor | `data_conversion_hub.dmd2.expand_samples_to_train_pairs` | `loss_hub.dmd2.prepare_generator_batch` | `dmd2_loss_formula` | `select_scored_pairs` / – |
| `dmd2`, critic | (the actor's pairs) | `loss_hub.dmd2.prepare_critic_batch` | `critic_loss_formula` | – / `score_last_step_samples` |

`sft_loss` requires the convert and rollout-log paths, plus `--train-only` and a rollout function
that runs no engines (e.g. `miles.rollout.sft_rollout.generate_rollout`; see
`scripts/run_diffusion_sft_wan22.py`). `custom_loss` is the only loss type that reads the four hook
flags (`--custom-prepare-train-batch-path`, `--custom-loss-function-path`,
`--custom-train-input-postprocess-path`, `--custom-train-output-function-path`): any hook left unset
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):
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
objective.
Expand Down Expand Up @@ -278,9 +283,9 @@ def prepare(ctx, batch, *, pad_to_len=None) -> PreparedBatch:
...
```

Builds DiT inputs from train pairs. Defaults:
`miles.backends.fsdp_utils.loss_hub.flow_grpo.prepare_flow_grpo_batch` or the NFT
equivalent under `loss_hub.nft`. `PreparedBatch.latents`, `timesteps` and
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.
`PreparedBatch.latents`, `timesteps` and
`timesteps_for_model` are keyed by latent stream name: `"visual"`, plus e.g.
`"audio"` for joint audio-video models.

Expand All @@ -291,8 +296,9 @@ def loss_formula(ctx, batch, prepared, *, new_pred, old_pred, ref_pred, metrics,
...
```

`new_pred`, `old_pred` and `ref_pred` are keyed by the same stream names as `prepared.latents`.
`old_pred` is `None` unless `--loss-type nft`; `ref_pred` is `None` with `--ref-mode none`.
Read only under `--loss-type custom_loss`. `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`.

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

Expand All @@ -301,7 +307,8 @@ def train_input(ctx, train_pairs) -> list:
...
```

Preprocesses this rank's train pairs, the rollout output after conversion, before they are split into
Read only under `--loss-type custom_loss`. Preprocesses this rank's train pairs, the rollout output after
conversion, before they are split into
micro-batches and optimizer steps. It may filter, reorder or rewrite them, and returns the pairs to
train on. `ctx` is the context the prepare, loss and train-output hooks get, so earlier trainer
groups' outputs are already in `ctx.external_data`. The micro-batch schedule, the training forwards
Expand All @@ -314,7 +321,8 @@ def train_output(ctx, train_pairs) -> Any:
...
```

Runs without grad after this trainer group's train steps on a rollout. Every trainer group that
Read only under `--loss-type custom_loss`. Runs without grad after this trainer group's train steps on a
rollout. Every trainer group that
trains later on the same rollout reads the return value of its paired rank (same rank, same
train pairs) as `ctx.external_data[<role>]`. Prepare and loss hooks see the current optimizer step
as `ctx.optim_step_idx` and can leave inputs for this hook in `ctx.train_output_inputs`, which
Expand Down
49 changes: 8 additions & 41 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, flow_grpo_loss_formula, prepare_flow_grpo_batch
from .loss_hub import DiffusionLossContext, 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 @@ -168,25 +168,7 @@ def init(self, args: Namespace, role: str, with_ref: bool = False) -> int: # ty
self.model = torch.nn.ModuleDict(self.models)

self.sde_backend = load_function(args.sde_step_backend_path)()

self.custom_prepare_train_batch_func = (
load_function(args.custom_prepare_train_batch_path)
if args.custom_prepare_train_batch_path is not None
else None
)
self.custom_loss_formula_func = (
load_function(args.custom_loss_function_path) if args.custom_loss_function_path is not None else None
)
self.custom_train_input_postprocess_func = (
load_function(args.custom_train_input_postprocess_path)
if args.custom_train_input_postprocess_path is not None
else None
)
self.custom_train_output_func = (
load_function(args.custom_train_output_function_path)
if args.custom_train_output_function_path is not None
else None
)
self.loss_hooks = get_loss_hooks(args, role)

if args.optimizer == "adam":
self.optimizer = torch.optim.AdamW(
Expand Down Expand Up @@ -386,8 +368,8 @@ def _train_core(self, rollout_id: int, rollout_data, external_data: dict[str, An
dp_rank=self.parallel_state.dp_rank,
external_data=external_data,
)
if self.custom_train_input_postprocess_func is not None:
train_pairs = self.custom_train_input_postprocess_func(loss_ctx, train_pairs)
if self.loss_hooks.train_input is not None:
train_pairs = self.loss_hooks.train_input(loss_ctx, train_pairs)

num_pairs = len(train_pairs)

Expand Down Expand Up @@ -504,9 +486,9 @@ def _train_core(self, rollout_id: int, rollout_data, external_data: dict[str, An
reduced = {f"train/{self._metric_role_tag()}{key}": value for key, value in metrics.reduce().items()}
self._log_metrics(rollout_id, reduced, step=self.global_step)

if self.custom_train_output_func is not None:
if self.loss_hooks.train_output is not None:
with torch.no_grad():
return self.custom_train_output_func(loss_ctx, train_pairs)
return self.loss_hooks.train_output(loss_ctx, train_pairs)

def _maybe_legacy_window_pad_len(self, train_pairs: list, microbatch_ranges: list) -> int | None:
"""LEGACY 2D parity: the whole-window max cond seq_len (like the legacy tile path), or
Expand All @@ -533,10 +515,7 @@ def _forward_train_pair_batch(
old_log_prob_from_new: bool = False,
) -> torch.Tensor | None:
"""Run one prepared diffusion micro-batch."""
if self.custom_prepare_train_batch_func is not None:
prepared = self.custom_prepare_train_batch_func(ctx, batch, pad_to_len=pad_to_len)
else:
prepared = prepare_flow_grpo_batch(ctx, batch, pad_to_len=pad_to_len)
prepared = self.loss_hooks.prepare(ctx, batch, pad_to_len=pad_to_len)
train_pipeline_config = self.train_pipeline_config
forward_dtype = self._forward_dtype

Expand Down Expand Up @@ -587,19 +566,7 @@ def _compute_noise_pred(model) -> dict[str, torch.Tensor]:
# PEFT re-enables adapter gradients on exit; reshard first so that lands on the shards, not gathered copies.
reshard_model(prepared.model)

if self.custom_loss_formula_func is not None:
return self.custom_loss_formula_func(
ctx,
batch,
prepared,
new_pred=new_pred,
old_pred=old_pred,
ref_pred=ref_pred,
metrics=metrics,
write_old_log_prob=write_old_log_prob,
old_log_prob_from_new=old_log_prob_from_new,
)
return flow_grpo_loss_formula(
return self.loss_hooks.formula(
ctx,
batch,
prepared,
Expand Down
Loading
Loading