Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
37 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
7dbfaf1
test(e2e): run the H3 DMD2 recipe as a 2-GPU proxy in CI
zhihengy Nov 10, 2026
daff1b5
test(e2e): record the H3 DMD2 standard on CI and name the test as a p…
zhihengy Nov 10, 2026
5c9da32
test(e2e): re-record the H3 DMD2 standard on sglang-miles
zhihengy Nov 11, 2026
a38350d
Merge main into dmd2/06b-h3-dmd2-e2e after the PRs below it landed
Rockdu Nov 11, 2026
f4cc1d8
Merge main into dmd2/06b-h3-dmd2-e2e for the flow-grpo test fix (#380)
zhihengy Nov 12, 2026
0b8a1fc
feat(fsdp): forward a prepared batch's forward-only batch without gra…
zhihengy Nov 20, 2026
f2f18e9
feat(dmd2): add --dmd2-critic-scoring original, the reference's separ…
zhihengy Nov 20, 2026
07a6f9d
refactor(fsdp): a prepare hook returns the stages of a micro-batch; t…
Rockdu Nov 25, 2026
3debb87
test(e2e): take the DMD2 proxy recipe, test and standard as #366 merg…
Rockdu Nov 25, 2026
f8ef14e
Merge main into dmd2/07c-original-scoring-in-trunk: the stream tests …
Rockdu Nov 25, 2026
f79998d
test(fsdp): the stream tests read the batch flow_grpo_batch builds, a…
Rockdu Nov 25, 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
8 changes: 5 additions & 3 deletions docs/advanced/dtype-control.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions docs/fsdp_model_roles.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
13 changes: 13 additions & 0 deletions docs/models/h3/h3.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
3 changes: 2 additions & 1 deletion docs/user-guide/cli-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand All @@ -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. |

Expand Down
34 changes: 23 additions & 11 deletions docs/user-guide/customization.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
):
...
```
Expand All @@ -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`

Expand Down
83 changes: 38 additions & 45 deletions miles/backends/fsdp_utils/actor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -525,81 +527,69 @@ 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,
enabled=forward_dtype != torch.float32 and train_pipeline_config.enable_autocast,
):
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)

Expand All @@ -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,
Expand Down
Loading
Loading