Skip to content
Open
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
6 changes: 4 additions & 2 deletions docs/user-guide/customization.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`

Expand Down Expand Up @@ -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`

Expand Down
1 change: 1 addition & 0 deletions miles/backends/fsdp_utils/actor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
1 change: 1 addition & 0 deletions miles/backends/fsdp_utils/configs/cosmos3.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
3 changes: 2 additions & 1 deletion miles/backends/fsdp_utils/configs/h3.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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
Expand Down
1 change: 1 addition & 0 deletions miles/backends/fsdp_utils/configs/ltx.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
2 changes: 2 additions & 0 deletions miles/backends/fsdp_utils/configs/qwen_image21.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
19 changes: 19 additions & 0 deletions miles/backends/fsdp_utils/loss_hub/flow_grpo.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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],
Expand All @@ -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,
Expand Down Expand Up @@ -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,
)


Expand Down
2 changes: 2 additions & 0 deletions miles/backends/fsdp_utils/loss_hub/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
1 change: 1 addition & 0 deletions miles/ray/data_conversion_hub/flow_grpo.py
Original file line number Diff line number Diff line change
Expand Up @@ -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],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
4 changes: 4 additions & 0 deletions tests/fast/backends/fsdp_utils/test_h3_streams.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
1 change: 1 addition & 0 deletions tests/fast/backends/fsdp_utils/test_loss_hub_dmd2.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
20 changes: 20 additions & 0 deletions tests/fast/backends/fsdp_utils/test_reference_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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):
Expand Down Expand Up @@ -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
Expand Down
91 changes: 88 additions & 3 deletions tests/fast/rollout/test_traj_window_convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
Loading