Skip to content

refactor(fsdp): run the DMD2 teacher forward in the actor, requested by the critic's prepare hook - #372

Merged
Rockdu merged 27 commits into
mainfrom
dmd2/08-teacher-in-trunk
Nov 11, 2026
Merged

Rockdu merged 27 commits into
mainfrom
dmd2/08-teacher-in-trunk

Conversation

@zhihengy

@zhihengy zhihengy commented Nov 11, 2026 •

Copy link
Copy Markdown
Collaborator

Stacked on #368 (the ctx-loop-state PR), which sits on #367 and #343: the diff here is the 2 commits above it. It does what #368 left to the DMD2 stack's author: the teacher forward moves out of the hooks into the trunk.

What

  • PreparedBatch.teacher_guidance_scale (default None): a prepare hook asks the trunk to run the frozen teacher (--teacher-load) on this micro-batch at that CFG scale; None runs no teacher.
  • _forward_train_pair_batch runs it the way it runs the reference: without grad, with CFG over prepared.neg_cond / joint_cond and the family's cfg_batching (and true_cfg_scale=None, since several families let it override guidance_scale), resharded right after, and hands the prediction to every loss formula as teacher_pred (None when not requested). It runs before the training forward, so the teacher's gathered parameters and its forward temporaries never share the GPU with the training activations. A request without --teacher-load is a ValueError.
  • DMD2 critic: prepare_critic_batch sets the scale on the scoring step and collates the rollout's negative cond for it (the missing-negative-cond check moves here, before any forward); critic_loss_formula keeps (sample_index, x0_real, x0_fake) from teacher_pred and the detached new_pred, before the x0-loss conversion; score_last_step_samples only packs them onto the host. _predict_velocity and _score_with_teacher's second copy of the forward wrapper are deleted.
  • DiffusionLossContext.teacher_models is removed: no hook forwards the teacher any more.
  • The other formulas (flow_grpo, sft, nft, dmd2) take teacher_pred=None.

Why

The hook contract is "DiT forward always stays in the FSDP actor; the loss hook only computes the objective" (customization.md): prepare turns data into model inputs, the loss turns model outputs into the objective, the train-output hook post-processes. The teacher forward in score_last_step_samples was the one forward a hook ran, with its own copy of the dtype-policy / autocast / compute_noise_pred wrapper. The teacher now follows the reference: the prepare hook declares the forward's inputs, the actor executes it, the loss consumes the prediction.

Behaviour ledger: the teacher forward count is unchanged (only the scoring step asks for it); it runs before the critic's forward instead of after the critic's steps; the scores are bitwise the same (below). A custom formula without **kwargs and without teacher_pred fails with TypeError (the documented signature has **kwargs); reading ctx.teacher_models is an AttributeError.

Validation

CPU, on this head:

check result
tests/fast (backends, utils, rollout, test_train_diffusion.py) 620 passed, 3 skipped, 2 failed: the two test_sft_read_media cases that fetch a sample from the Hub (this environment is offline), failing the same way on the base
test_loss_hub_dmd2.py the scoring step asks for the teacher and collates the negative cond for both CFG batching paths; earlier steps ask for nothing; scale 1 needs no negative cond; the kept x0 equal x_s - sigma v of each forward, carry no grad, and the critic still gets its gradient; a missing negative cond is rejected at prepare
test_reference_models.py the real _forward_train_pair_batch runs the teacher first, without grad, with (use_cfg, cfg_batching, guidance_scale, true_cfg_scale) of its own and the prepared batch's for the actor, reshards it, hands teacher_pred to the formula; no forward when the prepare hook does not ask; a request without a teacher is rejected
pre-commit run --files passes

GPU, 2x H200, the #366 e2e (test_h3_t2va_dmd2_16xGPU_single_node_2xGPU_proxy: 2 rollouts of 4 prompts, 2 critic steps, --deterministic-mode), this PR's base plus the e2e recipe commits vs this PR plus the same commits:

series result
every logged value except wall-clock timings and memory (critic loss, grad norms, the per-sigma losses, the actor's loss and DMD2 metrics; 124 values over 16 records) bitwise equal
train/critic-peak_memory_allocated_gb on the critic's 4 steps, train/peak_memory_allocated_gb on the actor's 2 identical to the hundredth of a GB (32.75-32.78 GB; the recipe keeps parameters and optimizer state on the host)
train/critic-device_memory_used_gb on the two scoring steps (device-wide, after the step) 47.8 GB before, 50.9 / 51.1 GB after: more memory reserved by the caching allocator, not more allocated; the teacher's gathered parameters now come and go before the critic's activations instead of after its steps

Both trees ran with this environment's torch 2.13 port of the FSDP param-dtype patch and the H3 snapshot path, which are not part of this PR.

Files

  • miles/backends/fsdp_utils/loss_hub/types.py: PreparedBatch.teacher_guidance_scale; teacher_models off the context
  • miles/backends/fsdp_utils/actor.py: the teacher forward in the trunk, teacher_pred to the formula
  • miles/backends/fsdp_utils/loss_hub/dmd2.py: prepare requests, loss keeps, train-output packs
  • miles/backends/fsdp_utils/loss_hub/{flow_grpo,sft,nft}.py: teacher_pred=None
  • docs/fsdp_model_roles.md, docs/user-guide/customization.md, docs/user-guide/cli-reference.md
  • tests/fast/backends/fsdp_utils/test_loss_hub_dmd2.py, test_reference_models.py, test_train_input_hook.py, tests/fast/utils/test_reference_arguments.py

Stack

#351 (--dmd2-critic-scoring original) is rebased on this next: its score_held_out_samples compute phase runs the critic and the teacher itself and becomes a forward-only train phase.

Checklist

  • pre-commit hooks pass on the changed files
  • Added/updated tests for new behaviour
  • pytest tests/fast is green except the known HF-offline media cases of this environment
  • If launch flags changed, python3 train_diffusion.py --help still parses (no flag changed)
  • If a public flag was added, it appears in the CLI reference docs (no flag added; --teacher-load's row updated)
  • If an example was added, it has a real walkthrough (no example added)

zhihengy and others added 15 commits November 11, 2026 06:53
`train` returned its train output directly, so the driver's ray.get on the
train refs pulled every rank's output into the controller before the next
group read it again from the object store. Return `Box(ray.put(output))`
like the rollout shards: the driver gets a small box, the payload stays in
the store until the paired rank of a later group unboxes it.

Also note the train-output hook as a `--teacher-load` consumer in
docs/fsdp_model_roles.md, which cli-reference.md already did.

Co-Authored-By: Claude Mythos 5.1 <noreply@anthropic.com>
train returns Box(ray.put(output)); the driver discarded its ray.get and
passed the task refs on, so the consumer's box.inner hit an ObjectRef.
Keep the boxes the way the rollout shards are kept.

Co-Authored-By: Claude Mythos 5.1 <noreply@anthropic.com>
…tprocess

Review on #338: `custom_train_input_postprocess_func` says what the hook
does, a post-processing step on the converted train pairs. The flag
follows the prepare hook's pattern: `--custom-train-input-postprocess-path`
sets `args.custom_train_input_postprocess_path`, loaded into
`self.custom_train_input_postprocess_func`. Docs and the hook test follow.

Co-Authored-By: Claude Mythos 5.1 <noreply@anthropic.com>
#338 renamed the hook to --custom-train-input-postprocess-path; the DMD2
defaults and the critic override still set custom_train_input_function_path,
so --loss-type dmd2 failed in parse_args.

Co-Authored-By: Claude Mythos 5.1 <noreply@anthropic.com>
miles/ray/rollout.py imports imageio_ffmpeg to mux the eval audio; the
GPU image had it only as a transitive dependency and the hosted CPU
suite not at all, so tests/fast/rollout/test_eval_media.py failed to
import there.

Co-Authored-By: Claude Mythos 5.1 <noreply@anthropic.com>
Rockdu and others added 9 commits November 11, 2026 04:53
Whether a hook forwards the teacher is the hook's business; the argument
layer cannot tell from --loss-type and the hook paths who will read it,
so the check only ever guessed. --teacher-load is now accepted under every
loss type (dmd2 still requires it).
Stop filling the --custom-*-path arguments on behalf of nft / dmd2 and
stop overriding them per trainer role: a group's prepare, formula,
train-input and train-output hooks come from loss_hub.LOSS_HOOKS keyed by
(loss_type, role), the way miles core's get_loss_function does. Only
custom_loss reads the path flags. The critic overrides shrink to the six
values that really differ (checkpoint, lr, load/save dirs, steps, batch).
A path given under any other loss type would be silently ignored now that
the table selects the hooks, so fail at parse time instead.
DMD2 has no log-prob ratio to recompute, and once the recompute loop
passes its real step index the critic's last window would run its
scoring prepare and formula a second time. sft_loss and nft already
reject the flag.
microbatch_id and optim_step_idx were written onto DiffusionLossContext
before every forward and read back by the hooks; the planned micro-batch
prefetch would race on them. They are now required keyword arguments of
every prepare and formula hook, passed by the two trunk loops; the
numbering is unchanged (training from 0, the old-log-prob recompute of
windows 1.. reuses their training forwards' numbers).
The DMD2 critic formula appended its scoring inputs to a list on the
context and the train-output hook read them back: a hook-to-hook channel
invisible in the call graph. The trunk now owns one list per train call
and passes it to the formulas and to the train-output hook.
Nothing writes the context after construction any more: it is the
rollout-level, read-only view the hooks share. eq=False keeps identity
comparison; a synthesized hash would fail on the dict fields.
zhihengy and others added 2 commits November 11, 2026 05:02
prepare_critic_batch did three things in one body: build the SFT batch,
pick the scoring step's grid range, and collate the teacher's CFG inputs.
The teacher part is its own function now, _request_teacher_forward, and
the two helpers it shared with #351 are back, so the critic's prepare
reads as SFT plus the last step's teacher request. No behaviour change.
@Rockdu
Rockdu force-pushed the dmd2/refactor-c-ctx-loop-state branch from b6aee00 to 60acc02 Compare November 11, 2026 13:03
@Rockdu
Rockdu force-pushed the dmd2/08-teacher-in-trunk branch from 9ea9eb3 to b9e206a Compare November 11, 2026 13:03
@Rockdu Rockdu added run-ci-fsdp Run FSDP domain tests on this PR run-ci-e2e Run e2e metric-regression tests on this PR labels Nov 11, 2026

@Rockdu Rockdu left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@Rockdu
Rockdu changed the base branch from dmd2/refactor-c-ctx-loop-state to main November 11, 2026 15:55
@Rockdu
Rockdu merged commit 182b080 into main Nov 11, 2026
8 of 13 checks passed
@Rockdu
Rockdu deleted the dmd2/08-teacher-in-trunk branch November 11, 2026 17:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

run-ci-e2e Run e2e metric-regression tests on this PR run-ci-fsdp Run FSDP domain tests on this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants