Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
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 sets `PreparedBatch.teacher_batch`, 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
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; 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 sets `PreparedBatch.teacher_batch`, 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
18 changes: 9 additions & 9 deletions docs/user-guide/customization.md
Original file line number Diff line number Diff line change
Expand Up @@ -258,8 +258,8 @@ formula keeps the critic's x0 from that step's forward, before the update, next
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 a fresh draw, as `PreparedBatch.forward_only_batch`; the formula keeps the x0 of that
batch's forwards instead.
scoring batch, at a fresh draw, as the teacher's input and as `PreparedBatch.actor_forward_batch`, the critic's
own no-grad 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 @@ -297,11 +297,11 @@ 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. `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`. `PreparedBatch.forward_only_batch` is a second
prepared batch the trunk forwards without grad before this one, through the teacher it asks for and its model; a
formula whose prepare sets it also receives `forward_only_teacher_pred` and `forward_only_pred`.
`"audio"` for joint audio-video models. `PreparedBatch.teacher_batch` is the frozen teacher's input
(`--teacher-load`): a prepared batch with the teacher's own CFG fields and `neg_cond` / `joint_cond`, forwarded
without grad before the training forward; the formula receives it as `teacher_pred`. `PreparedBatch.actor_forward_batch`
is a second input for the model's own no-grad forward before the training forward; a formula whose prepare sets it also
receives that prediction as `actor_forward_pred`. The EMA and reference forwards always use the training batch.

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

Expand All @@ -318,8 +318,8 @@ 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 `prepared.teacher_batch`, which the trunk runs before the training forward when the prepare
hook sets that batch, else `None`.

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

Expand Down
108 changes: 47 additions & 61 deletions miles/backends/fsdp_utils/actor.py
Original file line number Diff line number Diff line change
Expand Up @@ -530,88 +530,74 @@ def _forward_train_pair_batch(
train_pipeline_config = self.train_pipeline_config
forward_dtype = self._forward_dtype

def _forward_teacher_and_model(prepared):
"""``prepared``'s DiT forward by model, the teacher prediction it asks for and its model's prediction."""
def _model_inputs(batch_in) -> tuple:
# 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(
return 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),
latents=batch_in.latents,
timesteps=batch_in.timesteps_for_model,
conds=(batch_in.pos_cond, batch_in.neg_cond, batch_in.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]:
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,
)
def _compute_noise_pred(model, batch_in, inputs: tuple) -> dict[str, torch.Tensor]:
latents_in, timesteps_in, (pos_cond_in, neg_cond_in, joint_cond_in) = inputs
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=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
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)
return _compute_noise_pred, teacher_pred, _compute_noise_pred(prepared.model)
inputs = _model_inputs(prepared)

forward_only_preds = {}
if prepared.forward_only_batch is not None:
# The frozen teacher runs before the training forward, so its gather never overlaps the activations.
teacher_pred = None
if prepared.teacher_batch is not None:
teacher_batch = prepared.teacher_batch
if teacher_batch.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[teacher_batch.component_name]
with torch.no_grad():
_, forward_only_teacher_pred, forward_only_pred = _forward_teacher_and_model(
prepared.forward_only_batch
teacher_pred = _compute_noise_pred(teacher, teacher_batch, _model_inputs(teacher_batch))
# A no-grad forward leaves FSDP's root parameters gathered; sleep must move the shards.
reshard_model(teacher)

actor_forward_preds = {}
if prepared.actor_forward_batch is not None:
actor_forward_batch = prepared.actor_forward_batch
with torch.no_grad():
actor_forward_preds["actor_forward_pred"] = _compute_noise_pred(
actor_forward_batch.model, actor_forward_batch, _model_inputs(actor_forward_batch)
)
forward_only_preds = dict(
forward_only_pred=forward_only_pred, forward_only_teacher_pred=forward_only_teacher_pred
)

_compute_noise_pred, teacher_pred, new_pred = _forward_teacher_and_model(prepared)
new_pred = _compute_noise_pred(prepared.model, prepared, inputs)

# 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, inputs)

# 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, inputs)
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, inputs)
# PEFT re-enables adapter gradients on exit; reshard first so that lands on the shards, not gathered copies.
reshard_model(prepared.model)

Expand All @@ -628,5 +614,5 @@ def _compute_noise_pred(
train_output_inputs=train_output_inputs,
write_old_log_prob=write_old_log_prob,
old_log_prob_from_new=old_log_prob_from_new,
**forward_only_preds,
**actor_forward_preds,
)
Loading
Loading