diff --git a/docs/user-guide/customization.md b/docs/user-guide/customization.md index d4eed2185..e38085831 100644 --- a/docs/user-guide/customization.md +++ b/docs/user-guide/customization.md @@ -268,7 +268,8 @@ def expand_samples_to_train_pairs(args, samples, rewards, raw_rewards) -> dict: ... ``` -Default for Flow-GRPO lives under `miles/ray/data_conversion_hub/flow_grpo.py`. +Default for Flow-GRPO lives under `miles/ray/data_conversion_hub/flow_grpo.py`. It sets `denoising_step_index` on +every pair (the pair's 0-based step in its rollout's schedule), which a family whose forward depends on the step needs. ### `--custom-convert-samples-to-train-data-path` @@ -296,7 +297,8 @@ counts from 0; the old-log-prob recompute of windows 1.. passes their training f `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`. +the training forward; the formula receives it as `teacher_pred`. `PreparedBatch.denoising_step_indices` (`[B]` long) +reaches the family's forward; of the built-in hooks only Flow-GRPO's sets it, from the pairs' `denoising_step_index`. ### `--custom-loss-function-path` diff --git a/miles/backends/fsdp_utils/actor.py b/miles/backends/fsdp_utils/actor.py index b948f444c..4c2c6e290 100644 --- a/miles/backends/fsdp_utils/actor.py +++ b/miles/backends/fsdp_utils/actor.py @@ -554,6 +554,7 @@ def _compute_noise_pred( model=model, latents_input=latents_in, timesteps_input=timesteps_in, + denoising_step_indices=prepared.denoising_step_indices, pos_cond=pos_cond_in, neg_cond=neg_cond_in, joint_cond=joint_cond_in, diff --git a/miles/backends/fsdp_utils/configs/cosmos3.py b/miles/backends/fsdp_utils/configs/cosmos3.py index 827662b42..4d2e616b0 100644 --- a/miles/backends/fsdp_utils/configs/cosmos3.py +++ b/miles/backends/fsdp_utils/configs/cosmos3.py @@ -74,6 +74,7 @@ def compute_noise_pred( model: torch.nn.Module, latents_input: dict[str, torch.Tensor], timesteps_input: dict[str, torch.Tensor], + denoising_step_indices: torch.Tensor | None, pos_cond: dict | None, neg_cond: dict | None, joint_cond: dict | None, diff --git a/miles/backends/fsdp_utils/configs/h3.py b/miles/backends/fsdp_utils/configs/h3.py index 2b80d95c7..eeaf8e3c7 100644 --- a/miles/backends/fsdp_utils/configs/h3.py +++ b/miles/backends/fsdp_utils/configs/h3.py @@ -125,6 +125,7 @@ def compute_noise_pred( model: torch.nn.Module, latents_input: dict[str, torch.Tensor], timesteps_input: dict[str, torch.Tensor], + denoising_step_indices: torch.Tensor | None, pos_cond: dict | None, neg_cond: dict | None, joint_cond: dict | None, @@ -145,7 +146,7 @@ def compute_noise_pred( RL feeds the visual stream alone, so its audio rows stay zero at the video time. """ - del neg_cond, joint_cond, use_cfg, cfg_batching, guidance_scale, true_cfg_scale + del denoising_step_indices, neg_cond, joint_cond, use_cfg, cfg_batching, guidance_scale, true_cfg_scale cond = pos_cond visual = latents_input["visual"] device, dtype = visual.device, visual.dtype diff --git a/miles/backends/fsdp_utils/configs/ltx.py b/miles/backends/fsdp_utils/configs/ltx.py index 9b6ef9269..c2fc5196e 100644 --- a/miles/backends/fsdp_utils/configs/ltx.py +++ b/miles/backends/fsdp_utils/configs/ltx.py @@ -90,6 +90,7 @@ def compute_noise_pred( model: torch.nn.Module, latents_input: dict[str, torch.Tensor], timesteps_input: dict[str, torch.Tensor], + denoising_step_indices: torch.Tensor | None, pos_cond: dict | None, neg_cond: dict | None, joint_cond: dict | None, diff --git a/miles/backends/fsdp_utils/configs/qwen_image21.py b/miles/backends/fsdp_utils/configs/qwen_image21.py index 1dc55755a..5d93dd565 100644 --- a/miles/backends/fsdp_utils/configs/qwen_image21.py +++ b/miles/backends/fsdp_utils/configs/qwen_image21.py @@ -169,6 +169,7 @@ def compute_noise_pred( model: torch.nn.Module, latents_input: dict[str, torch.Tensor], timesteps_input: dict[str, torch.Tensor], + denoising_step_indices: torch.Tensor | None, pos_cond: dict | None, neg_cond: dict | None, joint_cond: dict | None, @@ -182,6 +183,7 @@ def compute_noise_pred( model=model, latents_input=latents_input, timesteps_input=timesteps_input, + denoising_step_indices=denoising_step_indices, pos_cond=pos_cond, neg_cond=neg_cond, joint_cond=joint_cond, diff --git a/miles/backends/fsdp_utils/configs/train_pipeline_config.py b/miles/backends/fsdp_utils/configs/train_pipeline_config.py index 82b0b0e4b..46e98bff9 100644 --- a/miles/backends/fsdp_utils/configs/train_pipeline_config.py +++ b/miles/backends/fsdp_utils/configs/train_pipeline_config.py @@ -143,6 +143,7 @@ def compute_noise_pred( model: torch.nn.Module, latents_input: dict[str, torch.Tensor], timesteps_input: dict[str, torch.Tensor], + denoising_step_indices: torch.Tensor | None, pos_cond: dict | None, neg_cond: dict | None, joint_cond: dict | None, diff --git a/miles/backends/fsdp_utils/loss_hub/flow_grpo.py b/miles/backends/fsdp_utils/loss_hub/flow_grpo.py index acb203b7f..0800420d3 100644 --- a/miles/backends/fsdp_utils/loss_hub/flow_grpo.py +++ b/miles/backends/fsdp_utils/loss_hub/flow_grpo.py @@ -2,6 +2,8 @@ from __future__ import annotations +import operator + import torch from miles.backends.fsdp_utils.loss_hub.score_centering import score_centering_term @@ -15,6 +17,21 @@ def _stack_pair_field(batch: list[dict], key: str, device: torch.device) -> torc return torch.stack([pair[key] for pair in batch]).to(device=device, dtype=torch.float32) +def _stack_denoising_step_indices(batch: list[dict], device: torch.device) -> torch.Tensor | None: + steps = [pair.get("denoising_step_index") for pair in batch] + if all(step is None for step in steps): + return None + if any(step is None for step in steps): + raise ValueError( + "only some pairs of this micro-batch carry denoising_step_index; an expander sets it on every pair or on none" + ) + try: + steps = [operator.index(step) for step in steps] + except TypeError as error: + raise ValueError(f"denoising_step_index must be an int or an integer tensor scalar: {error}") from error + return torch.tensor(steps, device=device) + + def prepare_flow_grpo_batch( ctx: DiffusionLossContext, batch: list[dict], @@ -40,6 +57,7 @@ def prepare_flow_grpo_batch( next_sigmas = _stack_pair_field(batch, "next_sigma", device) sigma_max = _stack_pair_field(batch, "sigma_max", device) log_prob_old = _stack_pair_field(batch, "log_prob_old", device) + denoising_step_indices = _stack_denoising_step_indices(batch, device) advantage = torch.tensor( [float(pair["advantage"]) for pair in batch], device=device, @@ -109,6 +127,7 @@ def prepare_flow_grpo_batch( "sigma_max": sigma_max, "log_prob_old": log_prob_old, }, + denoising_step_indices=denoising_step_indices, ) diff --git a/miles/backends/fsdp_utils/loss_hub/types.py b/miles/backends/fsdp_utils/loss_hub/types.py index 449d49a34..f73c980bc 100644 --- a/miles/backends/fsdp_utils/loss_hub/types.py +++ b/miles/backends/fsdp_utils/loss_hub/types.py @@ -71,3 +71,5 @@ class PreparedBatch: extras: dict[str, Any] = field(default_factory=dict) # CFG scale of the frozen teacher's no-grad forward on this batch; None runs no teacher forward. teacher_guidance_scale: float | None = None + # [B] long: each pair's 0-based denoising step in its rollout's schedule; None when the prepare hook has none + denoising_step_indices: torch.Tensor | None = None diff --git a/miles/ray/data_conversion_hub/flow_grpo.py b/miles/ray/data_conversion_hub/flow_grpo.py index 9712b0e93..f8614f843 100644 --- a/miles/ray/data_conversion_hub/flow_grpo.py +++ b/miles/ray/data_conversion_hub/flow_grpo.py @@ -132,6 +132,7 @@ def _build_per_timestep_features( return { "latent": [_own_row(all_latents[position[int(s)]]) for s in sde_idx], "next_latent": [_own_row(all_latents[position[int(s) + 1]]) for s in sde_idx], + "denoising_step_index": idx, "timestep": timesteps[idx], "sigma": sigmas[idx], "next_sigma": sigmas[idx + 1], diff --git a/tests/fast/backends/fsdp_utils/configs/test_qwen_image21.py b/tests/fast/backends/fsdp_utils/configs/test_qwen_image21.py index 9920be40f..f1987f6af 100644 --- a/tests/fast/backends/fsdp_utils/configs/test_qwen_image21.py +++ b/tests/fast/backends/fsdp_utils/configs/test_qwen_image21.py @@ -88,6 +88,7 @@ def test_compute_noise_pred_keeps_target_tail(): model=_TailDiT(), latents_input={"visual": latents}, timesteps_input={"visual": torch.tensor([0.5])}, + denoising_step_indices=None, pos_cond={}, neg_cond=None, joint_cond=None, diff --git a/tests/fast/backends/fsdp_utils/configs/test_train_pipeline_config_registry.py b/tests/fast/backends/fsdp_utils/configs/test_train_pipeline_config_registry.py index 9735eff5e..c3b77913e 100644 --- a/tests/fast/backends/fsdp_utils/configs/test_train_pipeline_config_registry.py +++ b/tests/fast/backends/fsdp_utils/configs/test_train_pipeline_config_registry.py @@ -90,6 +90,7 @@ def _call(self, **overrides): model=_CondBiasDiT(), latents_input={"visual": self.h}, timesteps_input={"visual": torch.tensor([3.0, 5.0])}, + denoising_step_indices=None, pos_cond=self.pos, neg_cond=self.neg, joint_cond=None, diff --git a/tests/fast/backends/fsdp_utils/test_h3_streams.py b/tests/fast/backends/fsdp_utils/test_h3_streams.py index 0f56dd4b0..f8178de55 100644 --- a/tests/fast/backends/fsdp_utils/test_h3_streams.py +++ b/tests/fast/backends/fsdp_utils/test_h3_streams.py @@ -109,6 +109,7 @@ def test_t2va_prediction_matches_the_sft_target_and_skips_padding_rows(): model=context.models["transformer"], latents_input=prepared.latents, timesteps_input=prepared.timesteps_for_model, + denoising_step_indices=prepared.denoising_step_indices, pos_cond=prepared.pos_cond, neg_cond=None, joint_cond=None, @@ -175,6 +176,7 @@ def _forward(model, latents, timesteps, cond): model=model, latents_input=latents, timesteps_input=timesteps, + denoising_step_indices=None, pos_cond=cond, neg_cond=None, joint_cond=None, @@ -229,6 +231,7 @@ def test_t2va_joint_pair_feeds_audio_at_its_own_time(has_soundtrack): model=model, latents_input=latents, timesteps_input={"visual": _timestep(0.25), "audio": _timestep(0.75)}, + denoising_step_indices=None, pos_cond=cond, neg_cond=None, joint_cond=None, @@ -420,6 +423,7 @@ def test_real_tiny_diffusers_h3_joint_sft_forward_and_backward(forward_dtype): model=model, latents_input=prepared.latents, timesteps_input=prepared.timesteps_for_model, + denoising_step_indices=prepared.denoising_step_indices, pos_cond=prepared.pos_cond, neg_cond=None, joint_cond=None, diff --git a/tests/fast/backends/fsdp_utils/test_loss_hub_dmd2.py b/tests/fast/backends/fsdp_utils/test_loss_hub_dmd2.py index aa3a08501..7a952560c 100644 --- a/tests/fast/backends/fsdp_utils/test_loss_hub_dmd2.py +++ b/tests/fast/backends/fsdp_utils/test_loss_hub_dmd2.py @@ -145,6 +145,7 @@ def _forward(config, model, prepared, *, use_cfg, cfg_batching, guidance_scale): model=model, latents_input=prepared.latents, timesteps_input=prepared.timesteps_for_model, + denoising_step_indices=prepared.denoising_step_indices, pos_cond=prepared.pos_cond, neg_cond=prepared.neg_cond, joint_cond=prepared.joint_cond, diff --git a/tests/fast/backends/fsdp_utils/test_reference_models.py b/tests/fast/backends/fsdp_utils/test_reference_models.py index e90e271a2..e32feca30 100644 --- a/tests/fast/backends/fsdp_utils/test_reference_models.py +++ b/tests/fast/backends/fsdp_utils/test_reference_models.py @@ -157,6 +157,7 @@ def make_actor_forward_harness( teacher_models=None, teacher_guidance_scale=None, true_cfg_scale=None, + denoising_step_indices=None, ): observed = {} prepared = SimpleNamespace( @@ -172,6 +173,7 @@ def make_actor_forward_harness( guidance_scale=1.0, true_cfg_scale=true_cfg_scale, teacher_guidance_scale=teacher_guidance_scale, + denoising_step_indices=denoising_step_indices, ) def prepare(ctx, batch, **kwargs): @@ -583,6 +585,24 @@ def test_the_teacher_runs_first_without_grad_with_its_own_cfg(cfg_batching): assert actor_call["true_cfg_scale"] == 7.0 +def test_the_family_forward_receives_the_prepared_denoising_steps(): + """The actor passes the prepared steps through unchanged; a head-per-step DiT would run another step's head.""" + denoising_step_indices = torch.tensor([3, 4]) + harness, _ = make_actor_forward_harness( + {"transformer": TinyComponent()}, + {}, + "transformer", + torch.ones(2, 3), + None, + denoising_step_indices=denoising_step_indices, + ) + + _run_forward(harness) + + [(_, actor_call)] = harness.train_pipeline_config.noise_pred_calls + assert actor_call["denoising_step_indices"] is denoising_step_indices + + def test_an_unguided_teacher_runs_without_cfg(): harness, _, _, teacher = _teacher_harness(1.0) harness.train_pipeline_config.cfg_batching = True diff --git a/tests/fast/rollout/test_traj_window_convert.py b/tests/fast/rollout/test_traj_window_convert.py index 14bffaf7c..985ed7101 100644 --- a/tests/fast/rollout/test_traj_window_convert.py +++ b/tests/fast/rollout/test_traj_window_convert.py @@ -12,13 +12,15 @@ the full trajectory (1), full trajectories without provenance keep the legacy behaviour (2), a missing window latent raises instead of mispairing (3), a non-contiguous kept set still pairs correctly (4), NFT reads x0 off a -final-step-only trajectory but rejects one ending anywhere else (5), and the -final SDE step pairs with next_sigma == 0 (6). +final-step-only trajectory but rejects one ending anywhere else (5), the +final SDE step pairs with next_sigma == 0 (6), and the trainer's prepare hook +hands each row of a micro-batch its own pair's step in the rollout, not its +position in the shipped window, or no steps when the pairs carry none (7). """ from tests.ci.ci_register import register_cpu_ci -register_cpu_ci(est_time=10, suite="stage-a-cpu", labels=[]) +register_cpu_ci(est_time=20, suite="stage-a-cpu", labels=[]) import pytest import torch @@ -91,6 +93,89 @@ def test_terminal_step_next_sigma_is_zero(): assert feats["next_sigma"].item() == 0.0 +def _prepare_pairs_of_two_windows(edit_pairs=lambda pairs: None): + """Two samples with different SDE windows, expanded and prepared as one micro-batch.""" + from types import SimpleNamespace + + from miles.backends.fsdp_utils.loss_hub.flow_grpo import prepare_flow_grpo_batch + from miles.ray.data_conversion_hub.flow_grpo import expand_samples_to_train_pairs + from miles.utils.types import DenoisingEnv + + class _Family: + cfg_batching = False + + def process_timestep_as_input(self, timesteps): + return timesteps + + def prepare_cond_kwargs(self, cond, device): + return {} + + def collate_cond_for_sample_batch(self, conds, device, pad_to_len=None): + return {} + + samples = [ + Sample( + index=index, + prompt="p", + train_metadata={"sde_step_indices": sde}, + dit_trajectory=_windowed(_full_traj(), kept), + denoising_env=DenoisingEnv(), + rollout_log_probs=torch.zeros(T), + ) + for index, (sde, kept) in enumerate([([2, 3], [2, 3, 4]), ([6, 7], [6, 7, 8])]) + ] + pairs = expand_samples_to_train_pairs(None, samples, [0.1, 0.2], [0.1, 0.2])["train_data"] + edit_pairs(pairs) + ctx = SimpleNamespace( + args=SimpleNamespace(diffusion_adv_clip_max=5.0, diffusion_guidance_scale=1.0, diffusion_true_cfg_scale=None), + device=torch.device("cpu"), + train_pipeline_config=_Family(), + models={"transformer": torch.nn.Identity()}, + ) + return prepare_flow_grpo_batch(ctx, pairs, microbatch_id=0, optim_step_idx=0) + + +def test_prepared_batch_carries_each_pairs_rollout_step(): + """Samples with different SDE windows share a micro-batch; a row given a neighbour's step runs its head.""" + + def emit_one_step_as_a_plain_int(pairs): + pairs[1]["denoising_step_index"] = int(pairs[1]["denoising_step_index"]) + + prepared = _prepare_pairs_of_two_windows(emit_one_step_as_a_plain_int) + + assert prepared.denoising_step_indices.tolist() == [2, 3, 6, 7] + assert prepared.denoising_step_indices.dtype == torch.long + assert torch.equal(prepared.extras["sigmas"], _full_traj().sigmas[[2, 3, 6, 7]]) + + +def test_pairs_without_a_step_prepare_without_step_indices(): + """An expander written before the key existed still feeds the families whose forward ignores the step.""" + + def drop_the_step(pairs): + for pair in pairs: + del pair["denoising_step_index"] + + assert _prepare_pairs_of_two_windows(drop_the_step).denoising_step_indices is None + + +def test_a_micro_batch_with_the_step_on_only_some_pairs_is_rejected(): + def drop_one_step(pairs): + del pairs[2]["denoising_step_index"] + + with pytest.raises(ValueError, match="only some pairs"): + _prepare_pairs_of_two_windows(drop_one_step) + + +def test_a_step_that_is_not_an_integer_is_rejected(): + """Truncating 2.7 to 2 would run the pair through another step's output head.""" + + def emit_one_step_as_a_float(pairs): + pairs[0]["denoising_step_index"] = float(pairs[0]["denoising_step_index"]) + 0.7 + + with pytest.raises(ValueError, match="denoising_step_index must be an int"): + _prepare_pairs_of_two_windows(emit_one_step_as_a_float) + + def test_missing_window_latent_raises(): with pytest.raises(ValueError, match="lacks latents"): _build(_windowed(_full_traj(), [2, 3])) # boundary latent 4 missing