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..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 for requests that run CFG" - ) + 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 6eb389b50..11dd83e50 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,33 @@ def build_rollout_generate_payload( return sampling_params +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. + + 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 + | { + "seed": args.rollout_seed, + "guidance_scale": args.rollout_neg_cond_guidance_scale, + "rollout_stop_step_index": 0, + # no rollout's release would own a stored copy + "rollout_return_outputs_via_store": False, + }, + prompt="", + ) + bodies = await post(f"http://{args.sglang_router_ip}:{args.sglang_router_port}/rollout/generate", payload) + 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): """Global state for sglang-diffusion image rollout.""" @@ -140,6 +171,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() @@ -344,6 +376,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 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 @@ -414,6 +452,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..51f375696 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", @@ -2250,12 +2253,17 @@ 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 + 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..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, ) @@ -373,6 +374,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..a85ebaa54 --- /dev/null +++ b/tests/fast/rollout/test_rollout_neg_cond.py @@ -0,0 +1,141 @@ +"""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, 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 +""" + +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 +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 + +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_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) + return _reply(with_neg_cond=True) + + monkeypatch.setattr(rollout_module, "post", post) + sampling_params = { + "negative_prompt": "blurry", + "width": 512, + "guidance_scale": 1.0, + "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["negative_prompt"], sent["width"]) == ("blurry", 512) + assert (sent["guidance_scale"], sent["rollout_stop_step_index"]) == (4.5, 0) + assert not sent["rollout_return_outputs_via_store"] + 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.""" + + 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 fetch_neg_cond(args, sampling_params): + fetches.append(sampling_params) + return fetched + + monkeypatch.setattr(rollout_module, "GenerateState", lambda args: state) + monkeypatch.setattr(rollout_module, "fetch_neg_cond", fetch_neg_cond) + args = SimpleNamespace( + 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, + ) + + 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 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_loss_type_recipes_parse.py b/tests/fast/utils/test_loss_type_recipes_parse.py index 1a0868cbd..0356b3479 100644 --- a/tests/fast/utils/test_loss_type_recipes_parse.py +++ b/tests/fast/utils/test_loss_type_recipes_parse.py @@ -95,6 +95,28 @@ 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 + 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): + """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"