From 5d9c82c1372cd552460c1817be37606e05a6d4cb Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:41:41 +0000 Subject: [PATCH 1/8] feat(dmd2): fetch the negative cond of unguided rollouts for a teacher that runs CFG One request with CFG on, stopped after its first step, per run; its negative cond goes to every training sample that has none. --dmd2-teacher-guidance-scale > 1 could not run before: the student samples unguided, and the engine returns a negative cond only for a request that runs CFG. --- docs/user-guide/cli-reference.md | 2 +- miles/backends/fsdp_utils/loss_hub/dmd2.py | 2 +- miles/rollout/sglang_diffusion_rollout.py | 37 +++++++- miles/utils/arguments.py | 17 +++- .../rollout/test_generated_output_store.py | 1 + tests/fast/rollout/test_rollout_neg_cond.py | 91 +++++++++++++++++++ tests/fast/rollout/test_rollout_store_refs.py | 1 + tests/fast/utils/test_dmd2_arguments.py | 3 + .../utils/test_loss_type_recipes_parse.py | 21 +++++ 9 files changed, 167 insertions(+), 8 deletions(-) create mode 100644 tests/fast/rollout/test_rollout_neg_cond.py diff --git a/docs/user-guide/cli-reference.md b/docs/user-guide/cli-reference.md index e84db4693..1199e28cc 100644 --- a/docs/user-guide/cli-reference.md +++ b/docs/user-guide/cli-reference.md @@ -290,7 +290,7 @@ See [Dtype Control](../advanced/dtype-control.md). | `--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`. | | `--no-diffusion-nft-adaptive-weight` | flag | off | | | `--dmd2-critic-steps-per-rollout` | int | `5` | Critic optimizer steps per rollout under `dmd2`, before the actor's single step. Each DP shard must split into this many steps. The last step's samples are scored by the critic before that step's update, and the actor trains on them only. | -| `--dmd2-teacher-guidance-scale` | float | – | Required by `dmd2`: the teacher's CFG scale when scoring the student's samples; `1` runs it unguided. | +| `--dmd2-teacher-guidance-scale` | float | – | Required by `dmd2`: the teacher's CFG scale when scoring the student's samples; `1` runs it unguided. Above `1` the rollout fetches the negative cond with one CFG request per run. | | `--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 σ². | | `--critic-load` | str | `--teacher-load` | `dmd2` only: HF pipeline checkpoint the critic starts from. Its checkpoints go to the sibling `<--save>_critic` dir. | diff --git a/miles/backends/fsdp_utils/loss_hub/dmd2.py b/miles/backends/fsdp_utils/loss_hub/dmd2.py index 371679c19..a97d8d821 100644 --- a/miles/backends/fsdp_utils/loss_hub/dmd2.py +++ b/miles/backends/fsdp_utils/loss_hub/dmd2.py @@ -68,7 +68,7 @@ def _request_teacher_forward( 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" + "which the engine returns only with a negative prompt (--diffusion-negative-prompt)" ) 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] diff --git a/miles/rollout/sglang_diffusion_rollout.py b/miles/rollout/sglang_diffusion_rollout.py index 6eb389b50..e10e991c8 100644 --- a/miles/rollout/sglang_diffusion_rollout.py +++ b/miles/rollout/sglang_diffusion_rollout.py @@ -18,13 +18,17 @@ from miles.rollout.filter_hub.base_types import MetricGatherer, call_dynamic_filter from miles.utils.async_utils import run from miles.utils.diffusion_data import Dataset as DiffusionDataset -from miles.utils.diffusion_rollout_response import RolloutImageResponseParserActor, read_generated_outputs +from miles.utils.diffusion_rollout_response import ( + RolloutImageResponseParserActor, + apply_rollout_image_response, + read_generated_outputs, +) from miles.utils.eval_config import EvalDatasetConfig from miles.utils.http_utils import post from miles.utils.misc import SingletonMeta, load_function from miles.utils.output_store import StoredTensor, StoredTensorReader, connect_output_store, record_dropped_samples from miles.utils.tracking_utils import logs_rollout_media -from miles.utils.types import Sample +from miles.utils.types import CondKwargs, Sample from .rm_hub import batched_async_rm @@ -112,6 +116,28 @@ def build_rollout_generate_payload( return sampling_params +async def fetch_neg_cond(args: Namespace, sampling_params: dict[str, Any]) -> CondKwargs | None: + """The negative cond of the run's samples, from one request that runs CFG and stops after its first step. + + A sample rolled out without CFG returns none. It depends on the negative prompt and the sample size, not on the + prompt or the seed, so one request serves every sample. + """ + payload = build_rollout_generate_payload( + sampling_params + | { + "seed": args.rollout_seed, + "guidance_scale": args.rollout_neg_cond_guidance_scale, + "rollout_stop_step_index": 0, + "rollout_return_dit_trajectory": False, + # the store's objects are released with their rollout + "rollout_return_outputs_via_store": False, + }, + prompt="", + ) + bodies = await post(f"http://{args.sglang_router_ip}:{args.sglang_router_port}/rollout/generate", payload) + return apply_rollout_image_response(Sample(), bodies[0]).denoising_env.neg_cond_kwargs + + class GenerateState(metaclass=SingletonMeta): """Global state for sglang-diffusion image rollout.""" @@ -140,6 +166,7 @@ def __init__(self, args: Namespace) -> None: self.output_reader = StoredTensorReader(self.output_store) if args.use_output_store else None # outputs of the running rollout still to keep for its media logging self.media_outputs_left = 0 + self.neg_cond: CondKwargs | None = None self.reset() @@ -265,6 +292,10 @@ async def generate_microgroup( st.attach(microgroup) if not evaluation: check_extra_stream_sde_args(args, microgroup) + for sample in microgroup: + # a sample that ran CFG, or whose engine always returns one, keeps its own + if sample.denoising_env.neg_cond_kwargs is None: + sample.denoising_env.neg_cond_kwargs = state.neg_cond # Stash the SDE/training step indices on each sample so _train_core can # slice the full-length trajectory & rollout_log_probs down to the window. @@ -414,6 +445,8 @@ async def generate_rollout_async( state = GenerateState(args) state.media_outputs_left = args.wandb_log_num_images if logs_rollout_media(args, rollout_id) else 0 + if args.rollout_neg_cond_guidance_scale is not None and state.neg_cond is None: + state.neg_cond = await fetch_neg_cond(args, state.sampling_params) # instantiate data filters dynamic_filter = ( diff --git a/miles/utils/arguments.py b/miles/utils/arguments.py index ec78f3686..a6489e43f 100644 --- a/miles/utils/arguments.py +++ b/miles/utils/arguments.py @@ -1105,7 +1105,10 @@ def add_algo_arguments(parser): "--dmd2-teacher-guidance-scale", type=float, default=None, - help="CFG scale of the frozen teacher when DMD2 scores the student's samples; 1 runs it unguided.", + help=( + "CFG scale of the frozen teacher when DMD2 scores the student's samples; 1 runs it unguided. " + "Above 1 the rollout fetches the negative cond with one CFG request per run." + ), ) parser.add_argument( "--dmd2-score-sigma-range", @@ -1906,6 +1909,10 @@ def set_default_diffusion_args(args) -> None: if args.critic_lr is None: args.critic_lr = args.lr + # An unguided rollout returns no negative cond; a teacher that runs CFG has the rollout fetch it at this scale. + teacher_runs_cfg = args.loss_type == "dmd2" and (args.dmd2_teacher_guidance_scale or 1) > 1 + args.rollout_neg_cond_guidance_scale = args.dmd2_teacher_guidance_scale if teacher_runs_cfg else None + if args.ref_mode is None: args.ref_mode = "lora_base" if any(beta > 0 for beta in args.diffusion_kl_beta.values()) else "none" @@ -2251,11 +2258,13 @@ def miles_validate_args(args): args.model_backend_path = cfg_cls.model_backend_path args.primary_stream = cfg_cls.primary_stream if not cfg_cls.supports_cfg_training and ( - args.diffusion_guidance_scale != 1.0 or args.diffusion_negative_prompt is not None + args.diffusion_guidance_scale != 1.0 + or args.diffusion_negative_prompt is not None + or args.rollout_neg_cond_guidance_scale is not None ): raise ValueError( - f"{cfg_cls.__name__} trains unguided (supports_cfg_training=False); set " - f"--diffusion-guidance-scale 1.0 and drop --diffusion-negative-prompt" + f"{cfg_cls.__name__} trains unguided (supports_cfg_training=False); set --diffusion-guidance-scale 1.0 " + f"and --dmd2-teacher-guidance-scale 1, and drop --diffusion-negative-prompt" ) if cfg_cls.tasks and args.diffusion_task not in cfg_cls.tasks: raise ValueError( diff --git a/tests/fast/rollout/test_generated_output_store.py b/tests/fast/rollout/test_generated_output_store.py index e8e614f97..87bd52b83 100644 --- a/tests/fast/rollout/test_generated_output_store.py +++ b/tests/fast/rollout/test_generated_output_store.py @@ -373,6 +373,7 @@ def remaining_batch_size(self): rollout_batch_size=1, over_sampling_batch_size=1, n_samples_per_prompt=1, + rollout_neg_cond_guidance_scale=None, ) with pytest.raises(_Stop): diff --git a/tests/fast/rollout/test_rollout_neg_cond.py b/tests/fast/rollout/test_rollout_neg_cond.py new file mode 100644 index 000000000..6c82bf57d --- /dev/null +++ b/tests/fast/rollout/test_rollout_neg_cond.py @@ -0,0 +1,91 @@ +"""A trainer that runs CFG on unguided rollouts gets their negative cond from one request that runs CFG. + + args.rollout_neg_cond_guidance_scale (dmd2 sets it when its teacher runs CFG) + + fetch_neg_cond --> the run's sampling params, with CFG at that scale, stopped after step 0, no + trajectory and inline tensors; returns the reply's negative cond + generate_microgroup --> a training sample without a negative cond gets the fetched one; + a sample that has its own keeps it +""" + +from tests.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=5, suite="stage-a-cpu", labels=[]) + +from types import SimpleNamespace + +import pytest +import torch +from safetensors.torch import save + +from miles.rollout import sglang_diffusion_rollout as rollout_module +from miles.utils.types import CondKwargs, DenoisingEnv, Sample + + +@pytest.mark.asyncio +async def test_the_fetch_runs_cfg_for_one_step_and_returns_the_replys_neg_cond(monkeypatch): + """Sent as an unguided sample's request, the reply has no negative cond; sent through the output store, its + tensors are deleted with the first rollout.""" + neg_embeds = torch.arange(6.0).reshape(2, 3) + sent = {} + + async def post(url, payload): + sent.update(payload) + wire = {"encoder_hidden_states": [{"__tensor__": True, "data": save({"t": neg_embeds})}]} + return [{"denoising_env": {"pos_cond_kwargs": wire, "neg_cond_kwargs": wire}}] + + monkeypatch.setattr(rollout_module, "post", post) + args = SimpleNamespace( + sglang_router_ip="router", sglang_router_port=0, rollout_seed=7, rollout_neg_cond_guidance_scale=4.5 + ) + sampling_params = { + "guidance_scale": 1.0, + "rollout_return_dit_trajectory": True, + "rollout_return_outputs_via_store": True, + } + + neg_cond = await rollout_module.fetch_neg_cond(args, sampling_params) + + assert torch.equal(neg_cond.encoder_hidden_states[0], neg_embeds) + assert (sent["guidance_scale"], sent["rollout_stop_step_index"]) == (4.5, 0) + assert not sent["rollout_return_dit_trajectory"] and not sent["rollout_return_outputs_via_store"] + assert sampling_params["guidance_scale"] == 1.0 + + +@pytest.mark.asyncio +async def test_a_training_sample_without_a_neg_cond_gets_the_fetched_one(monkeypatch): + """A sample left without one stops the teacher's CFG forward; overwriting an engine's own would swap in a + negative cond padded for another prompt.""" + fetched, own = CondKwargs(), CondKwargs() + parsed = [ + Sample(index=0, denoising_env=DenoisingEnv()), + Sample(index=1, denoising_env=DenoisingEnv(neg_cond_kwargs=own)), + ] + parser = SimpleNamespace(apply_raw=SimpleNamespace(remote=lambda pending, raw: parsed)) + state = SimpleNamespace( + step_strategy_fn=None, + next_parser_idx=lambda: 0, + parser_inflight=[0], + response_parsers=[parser], + neg_cond=fetched, + ) + + async def post(url, payload, raw): + return b"" + + monkeypatch.setattr(rollout_module, "GenerateState", lambda args: state) + monkeypatch.setattr(rollout_module, "post", post) + monkeypatch.setattr(rollout_module.ray, "get", lambda value: value) + args = SimpleNamespace( + sglang_router_ip="router", + sglang_router_port=0, + rollout_fetch_in_parser=False, + rollout_extra_stream_sde_args={}, + ) + + samples = await rollout_module.generate_microgroup( + args, [Sample(index=0), Sample(index=1)], {"seed": 0, "num_inference_steps": 2} + ) + + assert samples[0].denoising_env.neg_cond_kwargs is fetched + assert samples[1].denoising_env.neg_cond_kwargs is own diff --git a/tests/fast/rollout/test_rollout_store_refs.py b/tests/fast/rollout/test_rollout_store_refs.py index 7752326aa..7b3280874 100644 --- a/tests/fast/rollout/test_rollout_store_refs.py +++ b/tests/fast/rollout/test_rollout_store_refs.py @@ -63,6 +63,7 @@ def _args() -> Namespace: rollout_sample_filter_path=None, wandb_log_num_images=0, wandb_log_image_interval=1, + rollout_neg_cond_guidance_scale=None, ) diff --git a/tests/fast/utils/test_dmd2_arguments.py b/tests/fast/utils/test_dmd2_arguments.py index fb0ac64fc..803241012 100644 --- a/tests/fast/utils/test_dmd2_arguments.py +++ b/tests/fast/utils/test_dmd2_arguments.py @@ -63,6 +63,7 @@ def test_dmd2_critic_defaults_to_the_teacher_and_the_actor_lr(user, expected): ref_mode=None, diffusion_kl_beta={None: 0.0}, teacher_load="teacher", + dmd2_teacher_guidance_scale=1.0, lr=2e-6, **{"critic_load": None, "critic_lr": None, **user}, ) @@ -88,6 +89,7 @@ def test_dmd2_fills_the_expand_path_and_touches_no_hook_path(): ref_mode=None, diffusion_kl_beta={None: 0.0}, teacher_load="teacher", + dmd2_teacher_guidance_scale=1.0, lr=2e-6, critic_load=None, critic_lr=None, @@ -101,6 +103,7 @@ def test_dmd2_fills_the_expand_path_and_touches_no_hook_path(): "critic_load": "teacher", "critic_lr": 2e-6, "ref_mode": "none", + "rollout_neg_cond_guidance_scale": None, } diff --git a/tests/fast/utils/test_loss_type_recipes_parse.py b/tests/fast/utils/test_loss_type_recipes_parse.py index 1a0868cbd..8ed6a4fc9 100644 --- a/tests/fast/utils/test_loss_type_recipes_parse.py +++ b/tests/fast/utils/test_loss_type_recipes_parse.py @@ -95,6 +95,27 @@ def test_each_loss_type_recipe_parses_and_validates(parse, loss_type): assert args.loss_type == loss_type +@pytest.mark.parametrize(("teacher_scale", "fetch_scale"), [("1.0", None), ("4.5", 4.5)]) +def test_a_dmd2_teacher_that_runs_cfg_has_the_rollout_fetch_the_neg_cond(parse, teacher_scale, fetch_scale): + """The student's unguided rollouts return no negative cond; left unset, the teacher's first CFG forward fails.""" + argv = ARGV_BY_LOSS_TYPE["dmd2"].replace( + "--dmd2-teacher-guidance-scale 1.0", f"--dmd2-teacher-guidance-scale {teacher_scale}" + ) + assert parse(argv).rollout_neg_cond_guidance_scale == fetch_scale + assert parse(ARGV_BY_LOSS_TYPE["policy_loss"]).rollout_neg_cond_guidance_scale is None + + +def test_a_dmd2_teacher_that_runs_cfg_is_rejected_on_a_model_that_trains_unguided(parse, monkeypatch): + """Such a model's forward drops the negative branch, so the teacher would score unguided without any error.""" + from miles.backends.fsdp_utils.configs import train_pipeline_config + + monkeypatch.setattr(train_pipeline_config.get_train_pipeline_config_cls("sd3"), "supports_cfg_training", False) + with pytest.raises(ValueError, match="trains unguided"): + parse( + ARGV_BY_LOSS_TYPE["dmd2"].replace("--dmd2-teacher-guidance-scale 1.0", "--dmd2-teacher-guidance-scale 4.5") + ) + + def test_the_models_primary_stream_is_resolved_into_args(parse): """The rollout side keys train pairs by ``args.primary_stream``; left unresolved, it fails on the first GPU rollout.""" assert parse(ARGV_BY_LOSS_TYPE["policy_loss"]).primary_stream == "main" From d7d22c75033e18a6d90f4c8b30917f4d4a4eddad Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:07:13 +0000 Subject: [PATCH 2/8] fix(rollout): attach the fetched negative cond after either generate function A --custom-generate-function-path run fetched it and then dropped it, since only generate_microgroup attached it. The tests now also drive the fetch from generate_rollout_async and check that the run's negative prompt and size reach the request: both parts could be removed without a test failing. --- miles/rollout/sglang_diffusion_rollout.py | 10 +- .../rollout/test_generated_output_store.py | 1 + tests/fast/rollout/test_rollout_neg_cond.py | 120 ++++++++++++------ 3 files changed, 86 insertions(+), 45 deletions(-) diff --git a/miles/rollout/sglang_diffusion_rollout.py b/miles/rollout/sglang_diffusion_rollout.py index e10e991c8..f64457218 100644 --- a/miles/rollout/sglang_diffusion_rollout.py +++ b/miles/rollout/sglang_diffusion_rollout.py @@ -292,10 +292,6 @@ async def generate_microgroup( st.attach(microgroup) if not evaluation: check_extra_stream_sde_args(args, microgroup) - for sample in microgroup: - # a sample that ran CFG, or whose engine always returns one, keeps its own - if sample.denoising_env.neg_cond_kwargs is None: - sample.denoising_env.neg_cond_kwargs = state.neg_cond # Stash the SDE/training step indices on each sample so _train_core can # slice the full-length trajectory & rollout_log_probs down to the window. @@ -375,6 +371,12 @@ async def generate_and_rm_microgroup( else: microgroup = await generate_microgroup(args, microgroup, sampling_params, evaluation=evaluation) + if not evaluation and state.neg_cond is not None: + for sample in microgroup: + # a sample that ran CFG, or whose engine always returns one, keeps its own + if sample.denoising_env.neg_cond_kwargs is None: + sample.denoising_env.neg_cond_kwargs = state.neg_cond + # for the rm that need the whole group, we will not do the rm here if args.group_rm: return microgroup diff --git a/tests/fast/rollout/test_generated_output_store.py b/tests/fast/rollout/test_generated_output_store.py index 87bd52b83..cab60d9de 100644 --- a/tests/fast/rollout/test_generated_output_store.py +++ b/tests/fast/rollout/test_generated_output_store.py @@ -95,6 +95,7 @@ def _state(store, *, media_outputs_left=0): output_store=store, output_reader=StoredTensorReader(store) if store is not None else None, media_outputs_left=media_outputs_left, + neg_cond=None, ) diff --git a/tests/fast/rollout/test_rollout_neg_cond.py b/tests/fast/rollout/test_rollout_neg_cond.py index 6c82bf57d..ff8500c07 100644 --- a/tests/fast/rollout/test_rollout_neg_cond.py +++ b/tests/fast/rollout/test_rollout_neg_cond.py @@ -2,16 +2,19 @@ args.rollout_neg_cond_guidance_scale (dmd2 sets it when its teacher runs CFG) - fetch_neg_cond --> the run's sampling params, with CFG at that scale, stopped after step 0, no - trajectory and inline tensors; returns the reply's negative cond - generate_microgroup --> a training sample without a negative cond gets the fetched one; - a sample that has its own keeps it + fetch_neg_cond --> the run's sampling params, with CFG at that scale, stopped after step 0, no + trajectory and inline tensors; returns the reply's negative cond + generate_rollout_async --> fetches before the run's first rollout only + generate_and_rm_microgroup --> after either generate function, a training sample without a negative cond + gets the fetched one; a sample that has its own keeps it """ from tests.ci.ci_register import register_cpu_ci register_cpu_ci(est_time=5, suite="stage-a-cpu", labels=[]) +import asyncio +import contextlib from types import SimpleNamespace import pytest @@ -21,71 +24,106 @@ from miles.rollout import sglang_diffusion_rollout as rollout_module from miles.utils.types import CondKwargs, DenoisingEnv, Sample +NEG_EMBEDS = torch.arange(6.0).reshape(2, 3) +ARGS = SimpleNamespace( + sglang_router_ip="router", sglang_router_port=0, rollout_seed=7, rollout_neg_cond_guidance_scale=4.5 +) + + +def _reply(*, with_neg_cond): + wire = {"encoder_hidden_states": [{"__tensor__": True, "data": save({"t": NEG_EMBEDS})}]} + return [{"denoising_env": {"pos_cond_kwargs": wire, "neg_cond_kwargs": wire if with_neg_cond else None}}] + @pytest.mark.asyncio -async def test_the_fetch_runs_cfg_for_one_step_and_returns_the_replys_neg_cond(monkeypatch): - """Sent as an unguided sample's request, the reply has no negative cond; sent through the output store, its - tensors are deleted with the first rollout.""" - neg_embeds = torch.arange(6.0).reshape(2, 3) +async def test_the_fetch_runs_cfg_for_one_step_on_the_runs_params_and_returns_the_replys_neg_cond(monkeypatch): + """Sent as an unguided sample's request, the reply has no negative cond; sent without the run's negative prompt + or size, it has the one of another prompt or another size.""" sent = {} async def post(url, payload): sent.update(payload) - wire = {"encoder_hidden_states": [{"__tensor__": True, "data": save({"t": neg_embeds})}]} - return [{"denoising_env": {"pos_cond_kwargs": wire, "neg_cond_kwargs": wire}}] + return _reply(with_neg_cond=True) monkeypatch.setattr(rollout_module, "post", post) - args = SimpleNamespace( - sglang_router_ip="router", sglang_router_port=0, rollout_seed=7, rollout_neg_cond_guidance_scale=4.5 - ) sampling_params = { + "negative_prompt": "blurry", + "width": 512, "guidance_scale": 1.0, "rollout_return_dit_trajectory": True, "rollout_return_outputs_via_store": True, } - neg_cond = await rollout_module.fetch_neg_cond(args, sampling_params) + neg_cond = await rollout_module.fetch_neg_cond(ARGS, sampling_params) - assert torch.equal(neg_cond.encoder_hidden_states[0], neg_embeds) + assert torch.equal(neg_cond.encoder_hidden_states[0], NEG_EMBEDS) + assert (sent["negative_prompt"], sent["width"]) == ("blurry", 512) assert (sent["guidance_scale"], sent["rollout_stop_step_index"]) == (4.5, 0) assert not sent["rollout_return_dit_trajectory"] and not sent["rollout_return_outputs_via_store"] assert sampling_params["guidance_scale"] == 1.0 @pytest.mark.asyncio -async def test_a_training_sample_without_a_neg_cond_gets_the_fetched_one(monkeypatch): - """A sample left without one stops the teacher's CFG forward; overwriting an engine's own would swap in a - negative cond padded for another prompt.""" - fetched, own = CondKwargs(), CondKwargs() - parsed = [ - Sample(index=0, denoising_env=DenoisingEnv()), - Sample(index=1, denoising_env=DenoisingEnv(neg_cond_kwargs=own)), - ] - parser = SimpleNamespace(apply_raw=SimpleNamespace(remote=lambda pending, raw: parsed)) - state = SimpleNamespace( - step_strategy_fn=None, - next_parser_idx=lambda: 0, - parser_inflight=[0], - response_parsers=[parser], - neg_cond=fetched, - ) +async def test_the_neg_cond_is_fetched_before_the_first_rollout_only(monkeypatch): + """Without the fetch no sample gets a negative cond; fetched per rollout, every rollout pays a CFG request.""" + + class _Stop(Exception): + pass + + class FakeState: + media_outputs_left = None + neg_cond = None + sampling_params = {} + + @property + def remaining_batch_size(self): + raise _Stop + + state, fetched, fetches = FakeState(), CondKwargs(), [] - async def post(url, payload, raw): - return b"" + async def fetch_neg_cond(args, sampling_params): + fetches.append(sampling_params) + return fetched monkeypatch.setattr(rollout_module, "GenerateState", lambda args: state) - monkeypatch.setattr(rollout_module, "post", post) - monkeypatch.setattr(rollout_module.ray, "get", lambda value: value) + monkeypatch.setattr(rollout_module, "fetch_neg_cond", fetch_neg_cond) args = SimpleNamespace( - sglang_router_ip="router", - sglang_router_port=0, - rollout_fetch_in_parser=False, - rollout_extra_stream_sde_args={}, + rollout_global_dataset=True, + wandb_log_num_images=0, + wandb_log_image_interval=1, + dynamic_sampling_filter_path=None, + rollout_batch_size=1, + over_sampling_batch_size=1, + n_samples_per_prompt=1, + rollout_neg_cond_guidance_scale=4.5, ) - samples = await rollout_module.generate_microgroup( - args, [Sample(index=0), Sample(index=1)], {"seed": 0, "num_inference_steps": 2} + for rollout_id in (0, 1): + with pytest.raises(_Stop): + await rollout_module.generate_rollout_async(args, rollout_id, data_source=None) + + assert fetches == [state.sampling_params] and state.neg_cond is fetched + + +@pytest.mark.asyncio +@pytest.mark.parametrize("call_site", ["microgroup", "custom_generate"]) +async def test_a_training_sample_without_a_neg_cond_gets_the_fetched_one(monkeypatch, call_site): + """A sample left without one stops the teacher's CFG forward, whichever function generated it; overwriting an + engine's own would swap in a negative cond padded for another prompt.""" + fetched, own = CondKwargs(), CondKwargs() + state = SimpleNamespace(semaphore=asyncio.Semaphore(1), dp_rank_context=contextlib.nullcontext, neg_cond=fetched) + + async def generate(args, microgroup, sampling_params, evaluation=False): + return [Sample(denoising_env=DenoisingEnv()), Sample(denoising_env=DenoisingEnv(neg_cond_kwargs=own))] + + monkeypatch.setattr(rollout_module, "GenerateState", lambda args: state) + monkeypatch.setattr(rollout_module, "generate_microgroup", generate) + monkeypatch.setattr(rollout_module, "load_function", lambda path: generate) + args = SimpleNamespace( + custom_generate_function_path="custom.generate" if call_site == "custom_generate" else None, group_rm=True ) + samples = await rollout_module.generate_and_rm_microgroup(args, [Sample(), Sample()], {}) + assert samples[0].denoising_env.neg_cond_kwargs is fetched assert samples[1].denoising_env.neg_cond_kwargs is own From 4ab2a611e60113692ba08f5de86299ed752e5085 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:07:13 +0000 Subject: [PATCH 3/8] fix(rollout): stop at a fetch that returns no negative cond Without a negative prompt the engine runs no CFG, and the run went on through a rollout and the critic's first steps before the trainer raised. The trainer's check names no cause again: a custom rollout function or a saved batch reaches it too. --- miles/backends/fsdp_utils/loss_hub/dmd2.py | 5 +---- miles/rollout/sglang_diffusion_rollout.py | 10 ++++++++-- tests/fast/rollout/test_rollout_neg_cond.py | 15 ++++++++++++++- 3 files changed, 23 insertions(+), 7 deletions(-) diff --git a/miles/backends/fsdp_utils/loss_hub/dmd2.py b/miles/backends/fsdp_utils/loss_hub/dmd2.py index a97d8d821..8e4c90110 100644 --- a/miles/backends/fsdp_utils/loss_hub/dmd2.py +++ b/miles/backends/fsdp_utils/loss_hub/dmd2.py @@ -66,10 +66,7 @@ def _request_teacher_forward( 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 with a negative prompt (--diffusion-negative-prompt)" - ) + raise ValueError("--dmd2-teacher-guidance-scale > 1 needs the rollout's negative cond") 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: diff --git a/miles/rollout/sglang_diffusion_rollout.py b/miles/rollout/sglang_diffusion_rollout.py index f64457218..2dbe112bb 100644 --- a/miles/rollout/sglang_diffusion_rollout.py +++ b/miles/rollout/sglang_diffusion_rollout.py @@ -116,7 +116,7 @@ def build_rollout_generate_payload( return sampling_params -async def fetch_neg_cond(args: Namespace, sampling_params: dict[str, Any]) -> CondKwargs | None: +async def fetch_neg_cond(args: Namespace, sampling_params: dict[str, Any]) -> CondKwargs: """The negative cond of the run's samples, from one request that runs CFG and stops after its first step. A sample rolled out without CFG returns none. It depends on the negative prompt and the sample size, not on the @@ -135,7 +135,13 @@ async def fetch_neg_cond(args: Namespace, sampling_params: dict[str, Any]) -> Co prompt="", ) bodies = await post(f"http://{args.sglang_router_ip}:{args.sglang_router_port}/rollout/generate", payload) - return apply_rollout_image_response(Sample(), bodies[0]).denoising_env.neg_cond_kwargs + neg_cond = apply_rollout_image_response(Sample(), bodies[0]).denoising_env.neg_cond_kwargs + if neg_cond is None: + raise ValueError( + f"the request at guidance scale {args.rollout_neg_cond_guidance_scale} returned no negative cond; " + "the engine runs CFG only with a negative prompt (--diffusion-negative-prompt)" + ) + return neg_cond class GenerateState(metaclass=SingletonMeta): diff --git a/tests/fast/rollout/test_rollout_neg_cond.py b/tests/fast/rollout/test_rollout_neg_cond.py index ff8500c07..1cedd0eb0 100644 --- a/tests/fast/rollout/test_rollout_neg_cond.py +++ b/tests/fast/rollout/test_rollout_neg_cond.py @@ -3,7 +3,8 @@ args.rollout_neg_cond_guidance_scale (dmd2 sets it when its teacher runs CFG) fetch_neg_cond --> the run's sampling params, with CFG at that scale, stopped after step 0, no - trajectory and inline tensors; returns the reply's negative cond + trajectory and inline tensors; returns the reply's negative cond, + and raises when the reply has none generate_rollout_async --> fetches before the run's first rollout only generate_and_rm_microgroup --> after either generate function, a training sample without a negative cond gets the fetched one; a sample that has its own keeps it @@ -63,6 +64,18 @@ async def post(url, payload): assert sampling_params["guidance_scale"] == 1.0 +@pytest.mark.asyncio +async def test_a_reply_without_a_neg_cond_stops_the_run_at_the_fetch(monkeypatch): + """An engine without a negative prompt runs no CFG; accepted, the run would go on to its first scoring step.""" + + async def post(url, payload): + return _reply(with_neg_cond=False) + + monkeypatch.setattr(rollout_module, "post", post) + with pytest.raises(ValueError, match="returned no negative cond"): + await rollout_module.fetch_neg_cond(ARGS, {}) + + @pytest.mark.asyncio async def test_the_neg_cond_is_fetched_before_the_first_rollout_only(monkeypatch): """Without the fetch no sample gets a negative cond; fetched per rollout, every rollout pays a CFG request.""" From 8735c426b8ff143c7d20f0f14d5b0c46940577ff Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:07:13 +0000 Subject: [PATCH 4/8] Reword why the fetch keeps its tensors inline: no rollout's release would own a stored copy The comment said the store deletes it with the first rollout; nothing would delete it. --- miles/rollout/sglang_diffusion_rollout.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/miles/rollout/sglang_diffusion_rollout.py b/miles/rollout/sglang_diffusion_rollout.py index 2dbe112bb..7a2c69e70 100644 --- a/miles/rollout/sglang_diffusion_rollout.py +++ b/miles/rollout/sglang_diffusion_rollout.py @@ -129,7 +129,7 @@ async def fetch_neg_cond(args: Namespace, sampling_params: dict[str, Any]) -> Co "guidance_scale": args.rollout_neg_cond_guidance_scale, "rollout_stop_step_index": 0, "rollout_return_dit_trajectory": False, - # the store's objects are released with their rollout + # no rollout's release would own a stored copy "rollout_return_outputs_via_store": False, }, prompt="", From dc4e70514c499539028aaef009049f34e0d16d11 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:31:57 +0000 Subject: [PATCH 5/8] test(dmd2): give the non-DMD2 run a teacher scale, so the loss-type guard is checked Without the scale in its argv the assertion held with or without the guard. --- tests/fast/utils/test_loss_type_recipes_parse.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/fast/utils/test_loss_type_recipes_parse.py b/tests/fast/utils/test_loss_type_recipes_parse.py index 8ed6a4fc9..0356b3479 100644 --- a/tests/fast/utils/test_loss_type_recipes_parse.py +++ b/tests/fast/utils/test_loss_type_recipes_parse.py @@ -102,7 +102,8 @@ def test_a_dmd2_teacher_that_runs_cfg_has_the_rollout_fetch_the_neg_cond(parse, "--dmd2-teacher-guidance-scale 1.0", f"--dmd2-teacher-guidance-scale {teacher_scale}" ) assert parse(argv).rollout_neg_cond_guidance_scale == fetch_scale - assert parse(ARGV_BY_LOSS_TYPE["policy_loss"]).rollout_neg_cond_guidance_scale is None + other_loss = ARGV_BY_LOSS_TYPE["policy_loss"] + f" --dmd2-teacher-guidance-scale {teacher_scale}" + assert parse(other_loss).rollout_neg_cond_guidance_scale is None def test_a_dmd2_teacher_that_runs_cfg_is_rejected_on_a_model_that_trains_unguided(parse, monkeypatch): From 1044479e66de1b2b1ee65af1248bba7485ae898a Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:38:52 +0000 Subject: [PATCH 6/8] Derive the fetch scale in miles_validate_args, where the other derived args are set It sat with the defaults of unset flags, so the tests that pin what those defaults write had to carry it. --- miles/utils/arguments.py | 7 +++---- tests/fast/utils/test_dmd2_arguments.py | 3 --- 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/miles/utils/arguments.py b/miles/utils/arguments.py index a6489e43f..51f375696 100644 --- a/miles/utils/arguments.py +++ b/miles/utils/arguments.py @@ -1909,10 +1909,6 @@ def set_default_diffusion_args(args) -> None: if args.critic_lr is None: args.critic_lr = args.lr - # An unguided rollout returns no negative cond; a teacher that runs CFG has the rollout fetch it at this scale. - teacher_runs_cfg = args.loss_type == "dmd2" and (args.dmd2_teacher_guidance_scale or 1) > 1 - args.rollout_neg_cond_guidance_scale = args.dmd2_teacher_guidance_scale if teacher_runs_cfg else None - if args.ref_mode is None: args.ref_mode = "lora_base" if any(beta > 0 for beta in args.diffusion_kl_beta.values()) else "none" @@ -2257,6 +2253,9 @@ def miles_validate_args(args): if args.model_backend_path is None: args.model_backend_path = cfg_cls.model_backend_path args.primary_stream = cfg_cls.primary_stream + # An unguided rollout returns no negative cond; a teacher that runs CFG has the rollout fetch it at this scale. + teacher_runs_cfg = args.loss_type == "dmd2" and (args.dmd2_teacher_guidance_scale or 1) > 1 + args.rollout_neg_cond_guidance_scale = args.dmd2_teacher_guidance_scale if teacher_runs_cfg else None if not cfg_cls.supports_cfg_training and ( args.diffusion_guidance_scale != 1.0 or args.diffusion_negative_prompt is not None diff --git a/tests/fast/utils/test_dmd2_arguments.py b/tests/fast/utils/test_dmd2_arguments.py index 803241012..fb0ac64fc 100644 --- a/tests/fast/utils/test_dmd2_arguments.py +++ b/tests/fast/utils/test_dmd2_arguments.py @@ -63,7 +63,6 @@ def test_dmd2_critic_defaults_to_the_teacher_and_the_actor_lr(user, expected): ref_mode=None, diffusion_kl_beta={None: 0.0}, teacher_load="teacher", - dmd2_teacher_guidance_scale=1.0, lr=2e-6, **{"critic_load": None, "critic_lr": None, **user}, ) @@ -89,7 +88,6 @@ def test_dmd2_fills_the_expand_path_and_touches_no_hook_path(): ref_mode=None, diffusion_kl_beta={None: 0.0}, teacher_load="teacher", - dmd2_teacher_guidance_scale=1.0, lr=2e-6, critic_load=None, critic_lr=None, @@ -103,7 +101,6 @@ def test_dmd2_fills_the_expand_path_and_touches_no_hook_path(): "critic_load": "teacher", "critic_lr": 2e-6, "ref_mode": "none", - "rollout_neg_cond_guidance_scale": None, } From 0112522f654dc728b7e1641093960a9ce44ff544 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:38:52 +0000 Subject: [PATCH 7/8] Drop the fetch's trajectory override: two latents once per run are not worth a request field The reply's negative cond does not depend on it. --- miles/rollout/sglang_diffusion_rollout.py | 1 - tests/fast/rollout/test_rollout_neg_cond.py | 9 ++++----- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/miles/rollout/sglang_diffusion_rollout.py b/miles/rollout/sglang_diffusion_rollout.py index 7a2c69e70..270bf070e 100644 --- a/miles/rollout/sglang_diffusion_rollout.py +++ b/miles/rollout/sglang_diffusion_rollout.py @@ -128,7 +128,6 @@ async def fetch_neg_cond(args: Namespace, sampling_params: dict[str, Any]) -> Co "seed": args.rollout_seed, "guidance_scale": args.rollout_neg_cond_guidance_scale, "rollout_stop_step_index": 0, - "rollout_return_dit_trajectory": False, # no rollout's release would own a stored copy "rollout_return_outputs_via_store": False, }, diff --git a/tests/fast/rollout/test_rollout_neg_cond.py b/tests/fast/rollout/test_rollout_neg_cond.py index 1cedd0eb0..a85ebaa54 100644 --- a/tests/fast/rollout/test_rollout_neg_cond.py +++ b/tests/fast/rollout/test_rollout_neg_cond.py @@ -2,9 +2,9 @@ args.rollout_neg_cond_guidance_scale (dmd2 sets it when its teacher runs CFG) - fetch_neg_cond --> the run's sampling params, with CFG at that scale, stopped after step 0, no - trajectory and inline tensors; returns the reply's negative cond, - and raises when the reply has none + fetch_neg_cond --> the run's sampling params, with CFG at that scale, stopped after step 0, with + inline tensors; returns the reply's negative cond, and raises when the reply + has none generate_rollout_async --> fetches before the run's first rollout only generate_and_rm_microgroup --> after either generate function, a training sample without a negative cond gets the fetched one; a sample that has its own keeps it @@ -51,7 +51,6 @@ async def post(url, payload): "negative_prompt": "blurry", "width": 512, "guidance_scale": 1.0, - "rollout_return_dit_trajectory": True, "rollout_return_outputs_via_store": True, } @@ -60,7 +59,7 @@ async def post(url, payload): assert torch.equal(neg_cond.encoder_hidden_states[0], NEG_EMBEDS) assert (sent["negative_prompt"], sent["width"]) == ("blurry", 512) assert (sent["guidance_scale"], sent["rollout_stop_step_index"]) == (4.5, 0) - assert not sent["rollout_return_dit_trajectory"] and not sent["rollout_return_outputs_via_store"] + assert not sent["rollout_return_outputs_via_store"] assert sampling_params["guidance_scale"] == 1.0 From 9e15397e41f89abd84e0f1aa4ee5d99541684adb Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:38:52 +0000 Subject: [PATCH 8/8] Trim two comments of the fetch: a repeated sentence and a case DMD2's validation rules out The student never runs CFG under dmd2, so only an engine that always returns a negative cond keeps its own. --- miles/rollout/sglang_diffusion_rollout.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/miles/rollout/sglang_diffusion_rollout.py b/miles/rollout/sglang_diffusion_rollout.py index 270bf070e..11dd83e50 100644 --- a/miles/rollout/sglang_diffusion_rollout.py +++ b/miles/rollout/sglang_diffusion_rollout.py @@ -119,8 +119,8 @@ def build_rollout_generate_payload( async def fetch_neg_cond(args: Namespace, sampling_params: dict[str, Any]) -> CondKwargs: """The negative cond of the run's samples, from one request that runs CFG and stops after its first step. - A sample rolled out without CFG returns none. It depends on the negative prompt and the sample size, not on the - prompt or the seed, so one request serves every sample. + The negative cond depends on the negative prompt and the sample size, not on the prompt or the seed, so one + request serves every sample. """ payload = build_rollout_generate_payload( sampling_params @@ -378,7 +378,7 @@ async def generate_and_rm_microgroup( if not evaluation and state.neg_cond is not None: for sample in microgroup: - # a sample that ran CFG, or whose engine always returns one, keeps its own + # a sample whose engine always returns one keeps its own if sample.denoising_env.neg_cond_kwargs is None: sample.denoising_env.neg_cond_kwargs = state.neg_cond