From 35f00954ba604bdaa36f027861a28f9013aecb80 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:00:33 +0000 Subject: [PATCH 01/13] feat(h3-image): bridge a weight sync to the rollout's layout, the per-step heads as stacks h3_image had no train-to-rollout transform, so a sync of the DiT's weights sent the Diffusers layout as it is: the engine maps names but not layouts, and skips pdd_proj_out.* with a warning. Every weight but the heads goes through H3's transform. The heads of one suffix are held until every step's arrived and leave as one stack under the name sglang-d's weight update takes it by (sgl-project/sglang#51654); the prefix is read from sglang when a sync needs it, since a sglang-miles before that PR has no such constant and every family's bridge is imported with the adaptations package. --- .../fsdp_utils/adaptations/__init__.py | 1 + .../diffusers/h3_image/weight_bridge.py | 53 ++++++++++++++ .../h3_image/test_h3_image_weight_bridge.py | 69 +++++++++++++++++++ 3 files changed, 123 insertions(+) create mode 100644 miles/backends/fsdp_utils/models/diffusers/h3_image/weight_bridge.py create mode 100644 tests/fast/backends/fsdp_utils/models/diffusers/h3_image/test_h3_image_weight_bridge.py diff --git a/miles/backends/fsdp_utils/adaptations/__init__.py b/miles/backends/fsdp_utils/adaptations/__init__.py index 76729c390..3c502d88c 100644 --- a/miles/backends/fsdp_utils/adaptations/__init__.py +++ b/miles/backends/fsdp_utils/adaptations/__init__.py @@ -8,6 +8,7 @@ # MUST be last: importing a family's weight_bridge registers its ParamTransform into the registry above. from ..models.diffusers.h3 import weight_bridge as _h3_weight_bridge # noqa: F401,E402 # isort: skip +from ..models.diffusers.h3_image import weight_bridge as _h3_image_weight_bridge # noqa: F401,E402 # isort: skip __all__ = [ "ParamTransform", diff --git a/miles/backends/fsdp_utils/models/diffusers/h3_image/weight_bridge.py b/miles/backends/fsdp_utils/models/diffusers/h3_image/weight_bridge.py new file mode 100644 index 000000000..5a95ca79c --- /dev/null +++ b/miles/backends/fsdp_utils/models/diffusers/h3_image/weight_bridge.py @@ -0,0 +1,53 @@ +"""H3 Image train->rollout weight transform: H3's native-layout transform for the backbone, and the per-step +output heads as the stacks sglang-d's weight update takes them by.""" + +import re + +import torch + +from miles.backends.fsdp_utils.adaptations.weight_bridge import register_param_transform +from miles.backends.fsdp_utils.models.diffusers.h3.weight_bridge import _to_fl2va + +_PDD_HEAD_NAME = re.compile(r"^pdd_proj_out\.(\d+)\.(weight|bias)$") +# "weight" / "bias" -> the heads that arrived so far, by denoising step +_PENDING_PDD_HEADS: dict[str, dict[int, torch.Tensor]] = {} + + +def get_rollout_pdd_fused_heads_name_prefix() -> str: + """The prefix sglang-d's weight update takes a per-step head stack by; raises on an sglang-d that takes none.""" + try: + from sglang.multimodal_gen.configs.models.dits.minimax_h3 import MINIMAX_H3_PDD_FUSED_HEADS_WEIGHT_NAME_PREFIX + except ImportError as error: + raise RuntimeError( + "this sglang-d takes no per-step output heads in a weight update (it predates sgl-project/sglang#51654): " + "a sync that sends H3 Image's heads would leave the rollout on the heads it started with. Install an " + "sglang-d that takes them, or train a LoRA and sync it as adapters (--use-lora --lora-ipc-weight-sync)" + ) from error + return MINIMAX_H3_PDD_FUSED_HEADS_WEIGHT_NAME_PREFIX + + +def _is_pdd_head(name: str, param) -> bool: + return _PDD_HEAD_NAME.match(name) is not None + + +def _to_fused_pdd_heads(name: str, full: torch.Tensor, model) -> list[tuple[str, torch.Tensor]]: + """Stack the per-step output heads into the one tensor the rollout DiT serves them from. + + The trainer holds pdd_proj_out.{step}.{weight,bias}; sglang-d serves video_out.{weight,bias}[step], the layout of + the release's pdd_fused_heads.safetensors, and its weight update takes a whole stack. Each head arrives in its own + call, so hold them until the heads of every step are in. + """ + step, suffix = _PDD_HEAD_NAME.match(name).groups() + heads_by_step = _PENDING_PDD_HEADS.setdefault(suffix, {}) + heads_by_step[int(step)] = full + num_steps = len(model.pdd_proj_out) + if len(heads_by_step) < num_steps: + return [] + del _PENDING_PDD_HEADS[suffix] + stack = torch.stack([heads_by_step[step] for step in range(num_steps)]) + return [(f"{get_rollout_pdd_fused_heads_name_prefix()}video_out.{suffix}", stack)] + + +register_param_transform("h3_image", _is_pdd_head, _to_fused_pdd_heads) +# every other weight is H3's: the rollout loads the same native partition without the audio rows +register_param_transform("h3_image", lambda name, param: True, _to_fl2va) diff --git a/tests/fast/backends/fsdp_utils/models/diffusers/h3_image/test_h3_image_weight_bridge.py b/tests/fast/backends/fsdp_utils/models/diffusers/h3_image/test_h3_image_weight_bridge.py new file mode 100644 index 000000000..1cb04447c --- /dev/null +++ b/tests/fast/backends/fsdp_utils/models/diffusers/h3_image/test_h3_image_weight_bridge.py @@ -0,0 +1,69 @@ +""" +H3 Image full-weight sync: the per-step output heads the trainer holds -> the stacks the rollout serves. + + pdd_proj_out.0.weight --+ held until the heads of every step arrive + pdd_proj_out.1.weight --+ (each arrives in its own call) + pdd_proj_out.2.weight --+--> final_layer.pdd_fused_heads.video_out.weight [step, out, in] + +sglang-d keeps the heads outside its parameters and takes a stack by that name only: a head sent under its +trainer name is skipped with a warning, and the rollout keeps denoising with the heads it started with. + +Every other weight goes through H3's transform, registered for family "h3_image" beside the heads'. +""" + +from tests.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=15, suite="stage-a-cpu", labels=[]) + +from types import SimpleNamespace + +import pytest +import torch +from sglang.multimodal_gen.configs.models.dits import minimax_h3 as sglang_minimax_h3 + +from miles.backends.fsdp_utils.adaptations import get_param_transform +from miles.backends.fsdp_utils.models.diffusers.h3.weight_bridge import _to_fl2va +from miles.backends.fsdp_utils.models.diffusers.h3_image.weight_bridge import ( + _to_fused_pdd_heads, + get_rollout_pdd_fused_heads_name_prefix, +) + +NUM_STEPS = 3 +MODEL = SimpleNamespace(pdd_proj_out=[None] * NUM_STEPS) + + +def _head(step: int, suffix: str) -> torch.Tensor: + # every head holds its own value, so a head in another step's place shows up in the comparison + return torch.full((4, 5) if suffix == "weight" else (4,), float(step)) + + +@pytest.mark.parametrize("suffix", ["weight", "bias"]) +def test_heads_are_held_until_every_step_arrived_then_stacked_by_step(suffix): + assert _to_fused_pdd_heads(f"pdd_proj_out.2.{suffix}", _head(2, suffix), MODEL) == [] + assert _to_fused_pdd_heads(f"pdd_proj_out.0.{suffix}", _head(0, suffix), MODEL) == [] + [(name, stack)] = _to_fused_pdd_heads(f"pdd_proj_out.1.{suffix}", _head(1, suffix), MODEL) + + assert name == f"final_layer.pdd_fused_heads.video_out.{suffix}" + torch.testing.assert_close(stack, torch.stack([_head(step, suffix) for step in range(NUM_STEPS)])) + + +def test_the_next_sync_starts_from_no_held_heads(): + for _sync in range(2): + units = [_to_fused_pdd_heads(f"pdd_proj_out.{step}.bias", _head(step, "bias"), MODEL) for step in range(3)] + assert [len(unit) for unit in units] == [0, 0, 1] + + +def test_bridge_registers_h3_image_on_import(): + # registration rides on adaptations' imports; a family missing there syncs untransformed, heads included + assert get_param_transform("pdd_proj_out.0.weight", torch.zeros(1), "h3_image") is _to_fused_pdd_heads + assert get_param_transform("transformer_blocks.0.attn.to_q.weight", torch.zeros(1), "h3_image") is _to_fl2va + # the heads' transform is H3 Image's alone: H3 has one output head, which its own transform renames + assert get_param_transform("pdd_proj_out.0.weight", torch.zeros(1), "h3") is _to_fl2va + + +def test_an_sglang_that_takes_no_heads_is_named(monkeypatch): + """Sending the stacks under a name of our own would be skipped by that engine without an error.""" + monkeypatch.delattr(sglang_minimax_h3, "MINIMAX_H3_PDD_FUSED_HEADS_WEIGHT_NAME_PREFIX") + + with pytest.raises(RuntimeError, match="takes no per-step output heads"): + get_rollout_pdd_fused_heads_name_prefix() From be24faf9caa2a56061286e86d126667a2a1a7851 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:00:47 +0000 Subject: [PATCH 02/13] fix(h3-image): give every per-step head a gradient on every rank A forward runs the output head of one denoising step, so the other heads have no gradient on that rank. FSDP2 reduces the gradients of one wrap as a single buffer of the parameters that have one on that rank, in order, and the heads share a shape: two ranks with pairs of different steps line the buffers up head against head, and each head leaves the reduce with the mean of its own gradient and the other's. When the heads are trained, a forward hook on each head adds every head's parameters to its output at weight zero, so every rank reduces every head. The two-rank test fails without the hook: head 0's gradient differs from the mean of its own on every element on one rank and is missing on the other. --- miles/backends/fsdp_utils/configs/h3_image.py | 23 ++++ .../_h3_image_head_gradients_worker.py | 124 ++++++++++++++++++ .../test_h3_image_head_gradients.py | 42 ++++++ .../fsdp_utils/configs/test_h3_image.py | 21 +++ 4 files changed, 210 insertions(+) create mode 100644 tests/fast-gpu/backends/fsdp_utils/_h3_image_head_gradients_worker.py create mode 100644 tests/fast-gpu/backends/fsdp_utils/test_h3_image_head_gradients.py diff --git a/miles/backends/fsdp_utils/configs/h3_image.py b/miles/backends/fsdp_utils/configs/h3_image.py index ec0c7aa89..c860466d5 100644 --- a/miles/backends/fsdp_utils/configs/h3_image.py +++ b/miles/backends/fsdp_utils/configs/h3_image.py @@ -10,6 +10,23 @@ from .train_pipeline_config import register_train_pipeline_config +def _give_every_pdd_head_a_gradient(pdd_heads: torch.nn.ModuleList) -> None: + """Make whichever head a forward runs carry every head's parameters into the graph, at weight zero. + + A forward runs the head of one step, so the other heads have no gradient on that rank. FSDP reduces the + gradients of one wrap as a single buffer of the parameters that have one on that rank, in order: ranks whose + pairs come from different steps would average one head's gradient with another's. + """ + + def add_zero_of_every_head(head: torch.nn.Module, inputs: tuple, output: torch.Tensor) -> torch.Tensor: + # read at call time: FSDP swaps a module's sharded and unsharded parameters + zero = 0.0 * sum(parameter.sum() for pdd_head in pdd_heads for parameter in pdd_head.parameters()) + return output + zero.to(output.dtype) + + for pdd_head in pdd_heads: + pdd_head.register_forward_hook(add_zero_of_every_head) + + @register_train_pipeline_config("h3_image") class H3ImageTrainPipelineConfig(H3TrainPipelineConfig): """MiniMax H3 Image: the H3 DiT without audio rows, with one output head per denoising step.""" @@ -79,6 +96,12 @@ def apply_rollout_sampling_params( # the engine generates a request below its default area on a larger canvas and resizes the image back extra_sampling_params["min_generation_area"] = int(args.diffusion_width) * int(args.diffusion_height) + def postprocess_model_after_materialize(self, model: torch.nn.Module) -> None: + pdd_heads = model.pdd_proj_out + # a LoRA trainer and a frozen reference leave the heads without gradients on every rank + if any(parameter.requires_grad for parameter in pdd_heads.parameters()): + _give_every_pdd_head_a_gradient(pdd_heads) + def compute_noise_pred( self, *, diff --git a/tests/fast-gpu/backends/fsdp_utils/_h3_image_head_gradients_worker.py b/tests/fast-gpu/backends/fsdp_utils/_h3_image_head_gradients_worker.py new file mode 100644 index 000000000..eacb6be2c --- /dev/null +++ b/tests/fast-gpu/backends/fsdp_utils/_h3_image_head_gradients_worker.py @@ -0,0 +1,124 @@ +"""Worker for test_h3_image_head_gradients: two ranks, each with a pair from another denoising step.""" + +import os + +import diffusers +import torch +import torch.distributed as dist +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.packed_sequence import ( + minimax_h3_packed_sequence_ref2va_blocks, +) +from torch.distributed.fsdp import MixedPrecisionPolicy, fully_shard +from torch.distributed.tensor import distribute_tensor + +from miles.backends.fsdp_utils.configs.h3_image import H3ImageTrainPipelineConfig + +TEXT_LEN, LATENT_H, LATENT_W = 5, 8, 12 +NUM_IMAGE_ROWS = LATENT_H * LATENT_W // 4 +# the denoising step of each rank's pair; step 1's head runs on neither rank +STEP_BY_RANK = (0, 2) + + +def tiny_h3_image() -> torch.nn.Module: + torch.manual_seed(7) + return diffusers.MiniMaxH3ImageTransformer2DModel( + num_attention_heads=2, + attention_head_dim=16, + hidden_size=24, + num_layers=1, + num_refiner_layers=1, + ffn_dim=32, + in_channels=24, + patch_size=(1, 2, 2), + text_dim=8, + freq_dim=8, + time_embed_hidden_dim=24, + time_embed_dim=16, + rope_freq_dim=2, + num_pdd_heads=3, + ).cuda() + + +def backward_through_step(model: torch.nn.Module, step: int) -> None: + """One pair's loss through the head of ``step``; the pair itself is the same on every rank.""" + layout = minimax_h3_packed_sequence_ref2va_blocks( + text_len=TEXT_LEN, + latent_t=1, + latent_h=LATENT_H, + latent_w=LATENT_W, + audio_t=0, + ref_blocks=[], + seq_len=((TEXT_LEN + NUM_IMAGE_ROWS + 15) // 16) * 16 + 16, + ) + torch.manual_seed(11) + cond = { + "encoder_hidden_states": torch.randn(1, TEXT_LEN, 8, device="cuda"), + "h3_packed_layout": layout, + "h3_token_tags": layout["token_tags"], + } + prediction = H3ImageTrainPipelineConfig().compute_noise_pred( + model=model, + latents_input={"visual": torch.randn(1, NUM_IMAGE_ROWS, 96, device="cuda")}, + timesteps_input={"visual": torch.tensor([750.0], device="cuda")}, + denoising_step_indices=torch.tensor([step]), + pos_cond=cond, + neg_cond=None, + joint_cond=None, + use_cfg=False, + cfg_batching=False, + guidance_scale=1.0, + true_cfg_scale=None, + )["visual"] + prediction.square().sum().backward() + + +def mean_gradients_of_the_ranks() -> dict[str, torch.Tensor]: + """What each parameter's gradient must reduce to: the mean of the ranks' own, zero where a rank has none.""" + mean_gradients: dict[str, torch.Tensor] = {} + for step in STEP_BY_RANK: + plain = tiny_h3_image() + backward_through_step(plain, step) + for name, parameter in plain.named_parameters(): + gradient = torch.zeros_like(parameter) if parameter.grad is None else parameter.grad + mean_gradients[name] = mean_gradients.get(name, 0) + gradient / len(STEP_BY_RANK) + return mean_gradients + + +def main(): + local_rank = int(os.environ["LOCAL_RANK"]) + torch.cuda.set_device(local_rank) + dist.init_process_group("nccl", device_id=torch.device("cuda", local_rank)) + rank = dist.get_rank() + assert dist.get_world_size() == len(STEP_BY_RANK) + + # the same weights on every rank, wrapped as the loader wraps the DiT: each block, then the root with the heads + model = tiny_h3_image() + mp_policy = MixedPrecisionPolicy(param_dtype=torch.float32, reduce_dtype=torch.float32) + for block in model.transformer_blocks: + fully_shard(block, mp_policy=mp_policy) + fully_shard(model, mp_policy=mp_policy) + H3ImageTrainPipelineConfig().postprocess_model_after_materialize(model) + + backward_through_step(model, STEP_BY_RANK[rank]) + + mean_gradients = mean_gradients_of_the_ranks() + for name, parameter in model.named_parameters(): + gradient = parameter.grad + assert gradient is not None, f"{name} has no gradient on rank {rank}" + # this rank's shard of the mean, cut the way FSDP cut the parameter; no collective, so a rank that + # fails does not hang the other + mean_gradient_shard = distribute_tensor(mean_gradients[name], gradient.device_mesh, gradient.placements) + torch.testing.assert_close( + gradient.to_local(), + mean_gradient_shard.to_local(), + msg=lambda mismatch, name=name: f"{name} on rank {rank}: {mismatch}", + ) + + dist.barrier() + dist.destroy_process_group() + if rank == 0: + print("OK", flush=True) + + +if __name__ == "__main__": + main() diff --git a/tests/fast-gpu/backends/fsdp_utils/test_h3_image_head_gradients.py b/tests/fast-gpu/backends/fsdp_utils/test_h3_image_head_gradients.py new file mode 100644 index 000000000..640648d9b --- /dev/null +++ b/tests/fast-gpu/backends/fsdp_utils/test_h3_image_head_gradients.py @@ -0,0 +1,42 @@ +"""H3 Image full-weight training under FSDP2: ranks whose pairs come from different denoising steps. + + rank 0, pair of step 0: ... pdd_proj_out.0 FSDP reduces the gradients of one wrap as a single + rank 1, pair of step 2: ... pdd_proj_out.2 buffer of the parameters that have one, in order + +The heads have one shape, so the two buffers line up: without a gradient for every head on every rank, head 0 +leaves the reduce with the mean of its own gradient and head 2's, and so does head 2. +""" + +from tests.ci.ci_register import register_cuda_ci + +register_cuda_ci( + est_time=60, + suite="stage-b-5-gpu-h200", +) + +import os +import subprocess +import sys +from pathlib import Path + +import pytest + +_WORKER = Path(__file__).with_name("_h3_image_head_gradients_worker.py") + + +def test_each_head_reduces_to_the_mean_of_its_own_gradients(): + env = os.environ.copy() + env["PYTHONUNBUFFERED"] = "1" + result = subprocess.run( + [sys.executable, "-m", "torch.distributed.run", "--standalone", "--nnodes=1", "--nproc_per_node=2", _WORKER], + env=env, + capture_output=True, + text=True, + timeout=600, + ) + assert result.returncode == 0, result.stdout + result.stderr + assert "OK" in result.stdout + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v"])) diff --git a/tests/fast/backends/fsdp_utils/configs/test_h3_image.py b/tests/fast/backends/fsdp_utils/configs/test_h3_image.py index 5a3a5d7ff..0b872494b 100644 --- a/tests/fast/backends/fsdp_utils/configs/test_h3_image.py +++ b/tests/fast/backends/fsdp_utils/configs/test_h3_image.py @@ -146,6 +146,27 @@ def test_forward_rejects_a_layout_with_reference_rows(): _forward(_tiny_h3_image(), visual, cond, torch.tensor([0])) +def test_a_forward_through_one_head_gives_every_head_a_gradient(): + """FSDP reduces a wrap's gradients as one buffer of the parameters that have one on a rank, in order: a head + without a gradient on the ranks that ran another step would have its gradient averaged with that step's.""" + hooked, plain = _tiny_h3_image(), _tiny_h3_image() + H3ImageTrainPipelineConfig().postprocess_model_after_materialize(hooked) + visual, cond = _rows_and_cond(_t2i_layout()) + + predictions = [_forward(model, visual, cond, torch.tensor([1])) for model in (hooked, plain)] + for prediction in predictions: + prediction.square().sum().backward() + + assert torch.equal(*predictions) + plain_grads = {name: parameter.grad for name, parameter in plain.named_parameters()} + for name, parameter in hooked.named_parameters(): + if name.startswith("pdd_proj_out.") and not name.startswith("pdd_proj_out.1."): + assert plain_grads[name] is None + assert parameter.grad is not None and not parameter.grad.any(), name + else: + assert torch.equal(parameter.grad, plain_grads[name]), name + + def _grpo_args(**overrides): args = Namespace( loss_type="policy_loss", From 8f6f815c8bf0d1ac44049fb6522a14c670e208a6 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:00:47 +0000 Subject: [PATCH 03/13] feat(h3-image): accept full-weight training and merged LoRA syncs Both were refused because the rollout engine could not receive the per-step output heads and because the heads' gradients were not kept apart across ranks. A sync that carries the DiT's weights is now refused only on an sglang-d whose weight update takes no heads, at argument time. --- miles/backends/fsdp_utils/configs/h3_image.py | 18 +++--- .../fsdp_utils/configs/test_h3_image.py | 58 +++++++++++++++---- 2 files changed, 53 insertions(+), 23 deletions(-) diff --git a/miles/backends/fsdp_utils/configs/h3_image.py b/miles/backends/fsdp_utils/configs/h3_image.py index c860466d5..91ab68696 100644 --- a/miles/backends/fsdp_utils/configs/h3_image.py +++ b/miles/backends/fsdp_utils/configs/h3_image.py @@ -1,4 +1,4 @@ -"""MiniMax H3 Image: t2i Flow-GRPO on the release's PDD grid, LoRA only.""" +"""MiniMax H3 Image: t2i Flow-GRPO on the release's PDD grid.""" from __future__ import annotations @@ -38,6 +38,9 @@ class H3ImageTrainPipelineConfig(H3TrainPipelineConfig): @classmethod def validate_args(cls, args: Namespace) -> None: + from miles.backends.fsdp_utils.models.diffusers.h3_image.weight_bridge import ( + get_rollout_pdd_fused_heads_name_prefix, + ) from miles.utils.arguments import rollout_merges_lora if args.loss_type != "policy_loss": @@ -46,17 +49,10 @@ def validate_args(cls, args: Namespace) -> None: "denoising step, which no other built-in loss sets, and custom_loss is untested" ) has_trainer = not args.debug_rollout_only - if has_trainer and not args.use_lora: - raise ValueError( - "H3 Image runs its trainer with LoRA adapters only (--use-lora): full-weight training would update " - "the DiT's per-step output heads, each from the ranks whose pairs came from its step, which is untested" - ) + # every sync but a LoRA adapter one carries the DiT's weights, its per-step output heads among them; + # the lookup raises on an sglang-d whose weight update takes no heads if has_trainer and not args.train_only and not rollout_merges_lora(args): - raise ValueError( - "H3 Image syncs its LoRA as adapters (--lora-ipc-weight-sync under --colocate, plain --use-lora " - "otherwise): a merged sync sends the DiT's per-step output heads, which the rollout engine cannot " - "receive" - ) + get_rollout_pdd_fused_heads_name_prefix() if args.diffusion_flow_shift is not None: raise ValueError("H3 Image samples on its release's sigma grid; drop --diffusion-flow-shift") if args.sequence_parallel_size != 1: diff --git a/tests/fast/backends/fsdp_utils/configs/test_h3_image.py b/tests/fast/backends/fsdp_utils/configs/test_h3_image.py index 0b872494b..4f449b469 100644 --- a/tests/fast/backends/fsdp_utils/configs/test_h3_image.py +++ b/tests/fast/backends/fsdp_utils/configs/test_h3_image.py @@ -16,6 +16,7 @@ import diffusers import pytest import torch +from sglang.multimodal_gen.configs.models.dits import minimax_h3 as sglang_minimax_h3 from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.packed_sequence import ( minimax_h3_packed_sequence_ref2va_blocks, ) @@ -204,16 +205,60 @@ def test_lora_flow_grpo_is_accepted(): {"train_only": True, "lora_ipc_weight_sync": False, "colocate": True}, # engines on their own GPUs receive the adapters over NCCL {"colocate": False, "lora_ipc_weight_sync": False}, + # colocated without the IPC sync, the LoRA reaches the engine merged into the DiT's weights + {"lora_ipc_weight_sync": False}, + {"use_lora": False, "lora_ipc_weight_sync": False}, + {"use_lora": False, "lora_ipc_weight_sync": False, "train_only": True}, # the recipe's explicit one-pair tiles {"micro_batch_size_sample": 1, "micro_batch_size_tstep": 1}, {"diffusion_eval_num_steps": 6}, ], - ids=["rollout-only", "train-only", "adapters-over-nccl", "one-pair-tiles", "eval-steps-of-the-release"], + ids=[ + "rollout-only", + "train-only", + "adapters-over-nccl", + "lora-synced-as-merged-weights", + "full-weight", + "full-weight-train-only", + "one-pair-tiles", + "eval-steps-of-the-release", + ], ) def test_supported_variations_are_accepted(overrides): H3ImageTrainPipelineConfig.validate_args(_grpo_args(**overrides)) +@pytest.mark.parametrize( + ("overrides", "sync_sends_the_heads"), + [ + ({"use_lora": False, "lora_ipc_weight_sync": False}, True), + ({"lora_ipc_weight_sync": False}, True), + ({}, False), + ({"colocate": False, "lora_ipc_weight_sync": False}, False), + ({"use_lora": False, "lora_ipc_weight_sync": False, "train_only": True}, False), + ({"use_lora": False, "lora_ipc_weight_sync": False, "debug_rollout_only": True}, False), + ], + ids=[ + "full-weight", + "lora-synced-as-merged-weights", + "lora-adapters-over-ipc", + "lora-adapters-over-nccl", + "full-weight-train-only", + "rollout-only", + ], +) +def test_a_sync_that_sends_the_heads_needs_an_sglang_that_takes_them(monkeypatch, overrides, sync_sends_the_heads): + """That engine skips the heads with a warning, and its rollouts keep the heads it started with.""" + monkeypatch.delattr(sglang_minimax_h3, "MINIMAX_H3_PDD_FUSED_HEADS_WEIGHT_NAME_PREFIX") + args = _grpo_args(**overrides) + + if sync_sends_the_heads: + with pytest.raises(RuntimeError, match="takes no per-step output heads"): + H3ImageTrainPipelineConfig.validate_args(args) + else: + H3ImageTrainPipelineConfig.validate_args(args) + + def test_a_launch_with_the_required_flags_passes_the_real_parser(monkeypatch): """validate_args reads the parser's defaults, which a namespace built by hand does not have.""" argv = ( @@ -234,18 +279,9 @@ def test_a_launch_with_the_required_flags_passes_the_real_parser(monkeypatch): assert (args.micro_batch_size_sample, args.micro_batch_size_tstep) == (None, None) -def test_full_weight_training_is_rejected_even_without_an_engine(): - """--train-only syncs nothing, but every rank would still give a different per-step head its gradient.""" - with pytest.raises(ValueError, match="LoRA adapters only"): - H3ImageTrainPipelineConfig.validate_args(_grpo_args(train_only=True, use_lora=False)) - - @pytest.mark.parametrize( ("overrides", "message"), [ - ({"use_lora": False}, "LoRA adapters only"), - # merged base weights carry the per-step heads too - ({"lora_ipc_weight_sync": False}, "as adapters"), ({"loss_type": "nft"}, "policy_loss"), ({"diffusion_flow_shift": 3.0}, "flow-shift"), ({"sequence_parallel_size": 2}, "sequence"), @@ -262,8 +298,6 @@ def test_full_weight_training_is_rejected_even_without_an_engine(): ({"micro_batch_size": 2, "micro_batch_size_sample": 2, "micro_batch_size_tstep": 1}, "one pair"), ], ids=[ - "full-weight", - "lora-synced-as-merged-weights", "nft", "flow-shift", "sequence-parallel", From 566b5353f58c3b065c3a526b59de48f925b81c5d Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:23:13 +0000 Subject: [PATCH 04/13] fix(h3-image): refuse an engine without head updates as an argument error with a remedy that holds The refusal was a RuntimeError raised by a getter called for its side effect, and its remedy named `--lora-ipc-weight-sync` alone, which is refused without `--colocate`. The bridge now answers whether the engine takes head stacks, `validate_args` raises the ValueError with the remedy for both layouts, and the refusal of a config named by path names the weight transform it would also lose. --- miles/backends/fsdp_utils/configs/h3_image.py | 27 ++++++++++--------- .../diffusers/h3_image/weight_bridge.py | 23 ++++++++-------- .../fsdp_utils/configs/test_h3_image.py | 21 ++++++++++----- .../h3_image/test_h3_image_weight_bridge.py | 14 +--------- 4 files changed, 42 insertions(+), 43 deletions(-) diff --git a/miles/backends/fsdp_utils/configs/h3_image.py b/miles/backends/fsdp_utils/configs/h3_image.py index 90773c8b8..7e5c93ea0 100644 --- a/miles/backends/fsdp_utils/configs/h3_image.py +++ b/miles/backends/fsdp_utils/configs/h3_image.py @@ -38,9 +38,7 @@ class H3ImageTrainPipelineConfig(H3TrainPipelineConfig): @classmethod def validate_args(cls, args: Namespace) -> None: - from miles.backends.fsdp_utils.models.diffusers.h3_image.weight_bridge import ( - get_rollout_pdd_fused_heads_name_prefix, - ) + from miles.backends.fsdp_utils.models.diffusers.h3_image.weight_bridge import rollout_takes_pdd_fused_heads from miles.utils.arguments import rollout_merges_lora if args.loss_type != "policy_loss": @@ -48,16 +46,21 @@ def validate_args(cls, args: Namespace) -> None: "H3 Image trains with --loss-type policy_loss only: its DiT picks an output head by the rollout's " "denoising step, which no other built-in loss sets, and custom_loss is untested" ) - has_trainer = not args.debug_rollout_only - # every sync but a LoRA adapter one carries the DiT's weights, its per-step output heads among them; - # the lookup raises on an sglang-d whose weight update takes no heads - if has_trainer and not args.train_only and not rollout_merges_lora(args): - get_rollout_pdd_fused_heads_name_prefix() - if has_trainer and not args.train_only and args.diffusion_model_family != cls.model_family: + syncs_to_rollout = not args.debug_rollout_only and not args.train_only + # every sync but a LoRA adapter one carries the DiT's weights, its per-step output heads among them + if syncs_to_rollout and not rollout_merges_lora(args) and not rollout_takes_pdd_fused_heads(): + raise ValueError( + "H3 Image's weight sync sends the DiT's per-step output heads, which this sglang-d does not take in " + "a weight update (it predates sgl-project/sglang#51654): the rollout would keep the heads it started " + "with. Install an sglang-d that takes them, or train a LoRA and sync it as adapters (--use-lora, " + "with --lora-ipc-weight-sync under --colocate)" + ) + if syncs_to_rollout and args.diffusion_model_family != cls.model_family: raise ValueError( - "H3 Image named by --train-pipeline-config-path cannot sync to a rollout engine: the fused-qkv LoRA " - "group is looked up by --diffusion-model-family, which a config path leaves unset. Let " - "--hf-checkpoint or --diffusion-model-family name the family, or run --train-only" + "H3 Image named by --train-pipeline-config-path cannot sync to a rollout engine: its weight " + "transform and its fused-qkv LoRA group are looked up by --diffusion-model-family, which a config " + "path leaves unset. Let --hf-checkpoint or --diffusion-model-family name the family, or run " + "--train-only" ) if args.diffusion_flow_shift is not None: raise ValueError("H3 Image samples on its release's sigma grid; drop --diffusion-flow-shift") diff --git a/miles/backends/fsdp_utils/models/diffusers/h3_image/weight_bridge.py b/miles/backends/fsdp_utils/models/diffusers/h3_image/weight_bridge.py index 5a95ca79c..9eaccfd5c 100644 --- a/miles/backends/fsdp_utils/models/diffusers/h3_image/weight_bridge.py +++ b/miles/backends/fsdp_utils/models/diffusers/h3_image/weight_bridge.py @@ -13,17 +13,15 @@ _PENDING_PDD_HEADS: dict[str, dict[int, torch.Tensor]] = {} -def get_rollout_pdd_fused_heads_name_prefix() -> str: - """The prefix sglang-d's weight update takes a per-step head stack by; raises on an sglang-d that takes none.""" +def rollout_takes_pdd_fused_heads() -> bool: + """Whether this sglang-d's weight update takes a per-step head stack (sgl-project/sglang#51654).""" try: - from sglang.multimodal_gen.configs.models.dits.minimax_h3 import MINIMAX_H3_PDD_FUSED_HEADS_WEIGHT_NAME_PREFIX - except ImportError as error: - raise RuntimeError( - "this sglang-d takes no per-step output heads in a weight update (it predates sgl-project/sglang#51654): " - "a sync that sends H3 Image's heads would leave the rollout on the heads it started with. Install an " - "sglang-d that takes them, or train a LoRA and sync it as adapters (--use-lora --lora-ipc-weight-sync)" - ) from error - return MINIMAX_H3_PDD_FUSED_HEADS_WEIGHT_NAME_PREFIX + from sglang.multimodal_gen.configs.models.dits.minimax_h3 import ( # noqa: F401 + MINIMAX_H3_PDD_FUSED_HEADS_WEIGHT_NAME_PREFIX, + ) + except ImportError: + return False + return True def _is_pdd_head(name: str, param) -> bool: @@ -44,8 +42,11 @@ def _to_fused_pdd_heads(name: str, full: torch.Tensor, model) -> list[tuple[str, if len(heads_by_step) < num_steps: return [] del _PENDING_PDD_HEADS[suffix] + # imported here: every family's bridge loads with the adaptations package, also on an sglang-d without it + from sglang.multimodal_gen.configs.models.dits.minimax_h3 import MINIMAX_H3_PDD_FUSED_HEADS_WEIGHT_NAME_PREFIX + stack = torch.stack([heads_by_step[step] for step in range(num_steps)]) - return [(f"{get_rollout_pdd_fused_heads_name_prefix()}video_out.{suffix}", stack)] + return [(f"{MINIMAX_H3_PDD_FUSED_HEADS_WEIGHT_NAME_PREFIX}video_out.{suffix}", stack)] register_param_transform("h3_image", _is_pdd_head, _to_fused_pdd_heads) diff --git a/tests/fast/backends/fsdp_utils/configs/test_h3_image.py b/tests/fast/backends/fsdp_utils/configs/test_h3_image.py index ac59b79f0..dbec1fb29 100644 --- a/tests/fast/backends/fsdp_utils/configs/test_h3_image.py +++ b/tests/fast/backends/fsdp_utils/configs/test_h3_image.py @@ -252,7 +252,7 @@ def test_a_sync_that_sends_the_heads_needs_an_sglang_that_takes_them(monkeypatch args = _grpo_args(**overrides) if sync_sends_the_heads: - with pytest.raises(RuntimeError, match="takes no per-step output heads"): + with pytest.raises(ValueError, match="does not take in a weight update"): H3ImageTrainPipelineConfig.validate_args(args) else: H3ImageTrainPipelineConfig.validate_args(args) @@ -267,9 +267,10 @@ def test_a_sync_that_sends_the_heads_needs_an_sglang_that_takes_them(monkeypatch ) -def _validate_launch(monkeypatch, flags): +def _validate_launch(monkeypatch, flags, *, use_lora=True): """The parser and miles_validate_args on a launch line: the family hook reads what they derive before it.""" - monkeypatch.setattr(sys, "argv", shlex.split(_LAUNCH + flags)) + launch = _LAUNCH if use_lora else _LAUNCH.replace("--use-lora ", "") + monkeypatch.setattr(sys, "argv", shlex.split(launch + flags)) args = load_fsdp_args(extra_args_provider=get_miles_extra_args_provider()) set_default_diffusion_args(args) miles_validate_args(args) @@ -292,12 +293,18 @@ def test_a_run_on_dumped_rollouts_is_not_held_to_a_sync_mode(monkeypatch): assert _validate_launch(monkeypatch, "--load-debug-rollout-data dump/{rollout_id}.pt").train_only -def test_a_config_named_by_path_cannot_sync_to_an_engine(monkeypatch): - """Without the family key the fused-qkv LoRA group is not found, and the adapters of q, k and v can split.""" - path_flags = "--lora-ipc-weight-sync --train-pipeline-config-path miles.backends.fsdp_utils.configs.h3_image.H3ImageTrainPipelineConfig" +@pytest.mark.parametrize( + ("sync_flags", "use_lora"), + [("--lora-ipc-weight-sync ", True), ("", True), ("", False)], + ids=["lora-adapters", "lora-merged", "full-weight"], +) +def test_a_config_named_by_path_cannot_sync_to_an_engine(monkeypatch, sync_flags, use_lora): + """Without the family key neither the weight transform nor the fused-qkv LoRA group is found: a weight sync + would send the Diffusers layout as it is, and the adapters of q, k and v could split across buckets.""" + path = "--train-pipeline-config-path miles.backends.fsdp_utils.configs.h3_image.H3ImageTrainPipelineConfig" with pytest.raises(ValueError, match="cannot sync to a rollout engine"): - _validate_launch(monkeypatch, path_flags) + _validate_launch(monkeypatch, sync_flags + path, use_lora=use_lora) @pytest.mark.parametrize( diff --git a/tests/fast/backends/fsdp_utils/models/diffusers/h3_image/test_h3_image_weight_bridge.py b/tests/fast/backends/fsdp_utils/models/diffusers/h3_image/test_h3_image_weight_bridge.py index 1cb04447c..7ba58beca 100644 --- a/tests/fast/backends/fsdp_utils/models/diffusers/h3_image/test_h3_image_weight_bridge.py +++ b/tests/fast/backends/fsdp_utils/models/diffusers/h3_image/test_h3_image_weight_bridge.py @@ -19,14 +19,10 @@ import pytest import torch -from sglang.multimodal_gen.configs.models.dits import minimax_h3 as sglang_minimax_h3 from miles.backends.fsdp_utils.adaptations import get_param_transform from miles.backends.fsdp_utils.models.diffusers.h3.weight_bridge import _to_fl2va -from miles.backends.fsdp_utils.models.diffusers.h3_image.weight_bridge import ( - _to_fused_pdd_heads, - get_rollout_pdd_fused_heads_name_prefix, -) +from miles.backends.fsdp_utils.models.diffusers.h3_image.weight_bridge import _to_fused_pdd_heads NUM_STEPS = 3 MODEL = SimpleNamespace(pdd_proj_out=[None] * NUM_STEPS) @@ -59,11 +55,3 @@ def test_bridge_registers_h3_image_on_import(): assert get_param_transform("transformer_blocks.0.attn.to_q.weight", torch.zeros(1), "h3_image") is _to_fl2va # the heads' transform is H3 Image's alone: H3 has one output head, which its own transform renames assert get_param_transform("pdd_proj_out.0.weight", torch.zeros(1), "h3") is _to_fl2va - - -def test_an_sglang_that_takes_no_heads_is_named(monkeypatch): - """Sending the stacks under a name of our own would be skipped by that engine without an error.""" - monkeypatch.delattr(sglang_minimax_h3, "MINIMAX_H3_PDD_FUSED_HEADS_WEIGHT_NAME_PREFIX") - - with pytest.raises(RuntimeError, match="takes no per-step output heads"): - get_rollout_pdd_fused_heads_name_prefix() From bb338927019de62cccb08c5e887280725e472d51 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:23:13 +0000 Subject: [PATCH 05/13] test(h3-image): reduce the two ranks' head gradients under the loader's own FSDP wrapping The worker wrapped the blocks and the root by hand with stock policies. The hook is right only while every head is unsharded with the forward that runs one of them, which the family's plan decides: the worker now wraps through `apply_fsdp2` with that plan, so the patched reduce and a plan change are both in the test. The expected shard is cut locally (`src_data_rank=None`; the default scatters from rank 0), the tiny model and its layout come from the CPU test, and the test skips on fewer than two GPUs. --- .../_h3_image_head_gradients_worker.py | 76 +++++-------------- .../test_h3_image_head_gradients.py | 2 + 2 files changed, 23 insertions(+), 55 deletions(-) diff --git a/tests/fast-gpu/backends/fsdp_utils/_h3_image_head_gradients_worker.py b/tests/fast-gpu/backends/fsdp_utils/_h3_image_head_gradients_worker.py index eacb6be2c..1a14f6b2d 100644 --- a/tests/fast-gpu/backends/fsdp_utils/_h3_image_head_gradients_worker.py +++ b/tests/fast-gpu/backends/fsdp_utils/_h3_image_head_gradients_worker.py @@ -1,65 +1,28 @@ """Worker for test_h3_image_head_gradients: two ranks, each with a pair from another denoising step.""" import os +from argparse import Namespace -import diffusers import torch import torch.distributed as dist -from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.packed_sequence import ( - minimax_h3_packed_sequence_ref2va_blocks, -) -from torch.distributed.fsdp import MixedPrecisionPolicy, fully_shard +from tests.fast.backends.fsdp_utils.configs.test_h3_image import SIGMA, _rows_and_cond, _t2i_layout, _tiny_h3_image from torch.distributed.tensor import distribute_tensor from miles.backends.fsdp_utils.configs.h3_image import H3ImageTrainPipelineConfig +from miles.backends.fsdp_utils.model_backend import DiffusersModelBackend +from miles.backends.fsdp_utils.model_loader import apply_fsdp2 -TEXT_LEN, LATENT_H, LATENT_W = 5, 8, 12 -NUM_IMAGE_ROWS = LATENT_H * LATENT_W // 4 # the denoising step of each rank's pair; step 1's head runs on neither rank STEP_BY_RANK = (0, 2) -def tiny_h3_image() -> torch.nn.Module: - torch.manual_seed(7) - return diffusers.MiniMaxH3ImageTransformer2DModel( - num_attention_heads=2, - attention_head_dim=16, - hidden_size=24, - num_layers=1, - num_refiner_layers=1, - ffn_dim=32, - in_channels=24, - patch_size=(1, 2, 2), - text_dim=8, - freq_dim=8, - time_embed_hidden_dim=24, - time_embed_dim=16, - rope_freq_dim=2, - num_pdd_heads=3, - ).cuda() - - def backward_through_step(model: torch.nn.Module, step: int) -> None: """One pair's loss through the head of ``step``; the pair itself is the same on every rank.""" - layout = minimax_h3_packed_sequence_ref2va_blocks( - text_len=TEXT_LEN, - latent_t=1, - latent_h=LATENT_H, - latent_w=LATENT_W, - audio_t=0, - ref_blocks=[], - seq_len=((TEXT_LEN + NUM_IMAGE_ROWS + 15) // 16) * 16 + 16, - ) - torch.manual_seed(11) - cond = { - "encoder_hidden_states": torch.randn(1, TEXT_LEN, 8, device="cuda"), - "h3_packed_layout": layout, - "h3_token_tags": layout["token_tags"], - } + visual, cond = _rows_and_cond(_t2i_layout()) prediction = H3ImageTrainPipelineConfig().compute_noise_pred( model=model, - latents_input={"visual": torch.randn(1, NUM_IMAGE_ROWS, 96, device="cuda")}, - timesteps_input={"visual": torch.tensor([750.0], device="cuda")}, + latents_input={"visual": visual.cuda()}, + timesteps_input={"visual": torch.tensor([SIGMA * 1000.0], device="cuda")}, denoising_step_indices=torch.tensor([step]), pos_cond=cond, neg_cond=None, @@ -76,7 +39,7 @@ def mean_gradients_of_the_ranks() -> dict[str, torch.Tensor]: """What each parameter's gradient must reduce to: the mean of the ranks' own, zero where a rank has none.""" mean_gradients: dict[str, torch.Tensor] = {} for step in STEP_BY_RANK: - plain = tiny_h3_image() + plain = _tiny_h3_image().cuda() backward_through_step(plain, step) for name, parameter in plain.named_parameters(): gradient = torch.zeros_like(parameter) if parameter.grad is None else parameter.grad @@ -91,13 +54,15 @@ def main(): rank = dist.get_rank() assert dist.get_world_size() == len(STEP_BY_RANK) - # the same weights on every rank, wrapped as the loader wraps the DiT: each block, then the root with the heads - model = tiny_h3_image() - mp_policy = MixedPrecisionPolicy(param_dtype=torch.float32, reduce_dtype=torch.float32) - for block in model.transformer_blocks: - fully_shard(block, mp_policy=mp_policy) - fully_shard(model, mp_policy=mp_policy) - H3ImageTrainPipelineConfig().postprocess_model_after_materialize(model) + # the same weights on every rank, wrapped and postprocessed as the loader does it + model = _tiny_h3_image().cuda() + train_pipeline_config = H3ImageTrainPipelineConfig() + apply_fsdp2( + model, + DiffusersModelBackend(train_pipeline_config).fsdp_parallel_plan(model), + args=Namespace(diffusion_forward_dtype="fp32", fsdp_reduce_dtype="fp32"), + ) + train_pipeline_config.postprocess_model_after_materialize(model) backward_through_step(model, STEP_BY_RANK[rank]) @@ -105,9 +70,10 @@ def main(): for name, parameter in model.named_parameters(): gradient = parameter.grad assert gradient is not None, f"{name} has no gradient on rank {rank}" - # this rank's shard of the mean, cut the way FSDP cut the parameter; no collective, so a rank that - # fails does not hang the other - mean_gradient_shard = distribute_tensor(mean_gradients[name], gradient.device_mesh, gradient.placements) + # src_data_rank=None cuts this rank's shard locally: no collective, so a failing rank does not hang the other + mean_gradient_shard = distribute_tensor( + mean_gradients[name], gradient.device_mesh, gradient.placements, src_data_rank=None + ) torch.testing.assert_close( gradient.to_local(), mean_gradient_shard.to_local(), diff --git a/tests/fast-gpu/backends/fsdp_utils/test_h3_image_head_gradients.py b/tests/fast-gpu/backends/fsdp_utils/test_h3_image_head_gradients.py index 640648d9b..ca6d2e0ef 100644 --- a/tests/fast-gpu/backends/fsdp_utils/test_h3_image_head_gradients.py +++ b/tests/fast-gpu/backends/fsdp_utils/test_h3_image_head_gradients.py @@ -20,10 +20,12 @@ from pathlib import Path import pytest +import torch _WORKER = Path(__file__).with_name("_h3_image_head_gradients_worker.py") +@pytest.mark.skipif(torch.cuda.device_count() < 2, reason="Requires two CUDA devices") def test_each_head_reduces_to_the_mean_of_its_own_gradients(): env = os.environ.copy() env["PYTHONUNBUFFERED"] = "1" From a72ec8ab9c053762f320794d646af7bf7ccc175c Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:23:13 +0000 Subject: [PATCH 06/13] test(h3-image): send a tiny DiT through the updater, plain and with a merged LoRA The bridge tests call the transform directly. This drives the state dict through the weight iterator and its bucketing, with every tensor in a bucket of its own: the heads leave as the two stacks, and nothing leaves under a Diffusers name, also from a PEFT-wrapped model. --- .../fsdp_utils/test_h3_image_weight_sync.py | 93 +++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 tests/fast-gpu/backends/fsdp_utils/test_h3_image_weight_sync.py diff --git a/tests/fast-gpu/backends/fsdp_utils/test_h3_image_weight_sync.py b/tests/fast-gpu/backends/fsdp_utils/test_h3_image_weight_sync.py new file mode 100644 index 000000000..b32f09758 --- /dev/null +++ b/tests/fast-gpu/backends/fsdp_utils/test_h3_image_weight_sync.py @@ -0,0 +1,93 @@ +"""H3 Image weight sync through the trainer's updater: what the rollout engine is sent. + + state dict of the trainer's DiT (plain, or wrapped by PEFT with its LoRA merged in) + -> weight iterator -> family transform -> buckets + pdd_proj_out.{0,1,2}.{weight,bias} -> final_layer.pdd_fused_heads.video_out.{weight,bias} [step, ...] + +The heads arrive one by one, in buckets of their own here, and leave as two stacks; nothing leaves under a +Diffusers name, which the engine would load without its layout change or skip with a warning. +""" + +from tests.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=60, suite="stage-b-3-gpu-h200", labels=[]) + +from argparse import Namespace + +import diffusers +import pytest +import torch +from peft import LoraConfig, get_peft_model + +from miles.backends.fsdp_utils.diffusion_update_weight_utils import ( + DiffusionUpdateWeightFromTensor, + DiffusionUpdateWeightFromTensorLoRA, +) + + +class _CaptureFullWeightUpdater(DiffusionUpdateWeightFromTensor): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.buckets: list[list[tuple[str, torch.Tensor]]] = [] + + def update_bucket_weights(self, named_tensors, target_module): + self.buckets.append([(name, tensor.clone()) for name, tensor in named_tensors]) + + +class _CaptureMergedLoRAUpdater(DiffusionUpdateWeightFromTensorLoRA): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.buckets: list[list[tuple[str, torch.Tensor]]] = [] + + def update_bucket_weights(self, named_tensors, target_module): + self.buckets.append([(name, tensor.clone()) for name, tensor in named_tensors]) + + +def _tiny_h3_image(): + torch.manual_seed(7) + # one attention head of 128: the family transform regroups qkv rows by the release's head width + return diffusers.MiniMaxH3ImageTransformer2DModel( + num_attention_heads=1, + attention_head_dim=128, + hidden_size=128, + num_layers=1, + num_refiner_layers=1, + ffn_dim=32, + in_channels=24, + patch_size=(1, 2, 2), + text_dim=8, + freq_dim=8, + time_embed_hidden_dim=24, + time_embed_dim=16, + rope_freq_dim=2, + num_pdd_heads=3, + ).cuda() + + +@pytest.mark.parametrize("lora_merged_in", [False, True], ids=["full-weight", "merged-lora"]) +def test_a_weight_sync_sends_the_heads_as_two_stacks_and_no_diffusers_name(lora_merged_in): + model = _tiny_h3_image() + head_stacks = { + f"final_layer.pdd_fused_heads.video_out.{suffix}": torch.stack( + [getattr(head, suffix).detach().clone() for head in model.pdd_proj_out] + ) + for suffix in ("weight", "bias") + } + updater_cls = _CaptureFullWeightUpdater + if lora_merged_in: + model = get_peft_model(model, LoraConfig(r=4, lora_alpha=8, target_modules=["to_q", "to_k", "to_v"])) + updater_cls = _CaptureMergedLoRAUpdater + # one byte: every tensor closes its bucket, so the held heads outlive the buckets they arrived in + args = Namespace(update_weight_buffer_size=1, train_pipeline_config_path=None, diffusion_model_family="h3_image") + + updater = updater_cls(args, {"transformer": model}) + updater.update_weights() + + sent = [(name, tensor) for bucket in updater.buckets for name, tensor in bucket] + names = [name for name, _ in sent] + assert len(names) == len(set(names)) + assert not [name for name in names if name.startswith(("transformer_blocks.", "pdd_proj_out."))] + sent_head_stacks = {name: tensor for name, tensor in sent if "pdd" in name} + assert sent_head_stacks.keys() == head_stacks.keys() + for name, stack in head_stacks.items(): + assert torch.equal(sent_head_stacks[name], stack), name From 0599aaae8d224e5473bbbb9708f8c9bc3b503810 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:23:13 +0000 Subject: [PATCH 07/13] test(h3): the bridge is registered by adaptations' imports, no longer the last one --- .../fsdp_utils/models/diffusers/h3/test_h3_weight_bridge.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/fast/backends/fsdp_utils/models/diffusers/h3/test_h3_weight_bridge.py b/tests/fast/backends/fsdp_utils/models/diffusers/h3/test_h3_weight_bridge.py index 240b0faa8..9d144d927 100644 --- a/tests/fast/backends/fsdp_utils/models/diffusers/h3/test_h3_weight_bridge.py +++ b/tests/fast/backends/fsdp_utils/models/diffusers/h3/test_h3_weight_bridge.py @@ -9,7 +9,7 @@ Pushing [q; k; v] instead of per-head rows has the same shape, so the native qkv loader accepts it and silently scrambles attention. -The transform is registered for family "h3" by the last import in fsdp_utils/adaptations, +The transform is registered for family "h3" by the imports of fsdp_utils/adaptations, so it applies whenever the weight iterator uses the bridge. """ @@ -44,5 +44,5 @@ def test_qkv_is_held_until_complete_then_fused_per_head(): def test_bridge_registers_h3_on_import(): - # registration rides on adaptations' last import; a family missing there would sync untransformed + # registration rides on adaptations' imports; a family missing there would sync untransformed assert get_param_transform("transformer_blocks.0.attn.to_q.weight", torch.zeros(1), "h3") is _to_fl2va From 0d1589875dde5100ae309ece5a964aa54d15913e Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:35:36 +0000 Subject: [PATCH 08/13] test(h3-image): give the weight sync test the entry point CI runs a GPU file by --- .../backends/fsdp_utils/test_h3_image_weight_sync.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tests/fast-gpu/backends/fsdp_utils/test_h3_image_weight_sync.py b/tests/fast-gpu/backends/fsdp_utils/test_h3_image_weight_sync.py index b32f09758..79c3db219 100644 --- a/tests/fast-gpu/backends/fsdp_utils/test_h3_image_weight_sync.py +++ b/tests/fast-gpu/backends/fsdp_utils/test_h3_image_weight_sync.py @@ -12,6 +12,7 @@ register_cuda_ci(est_time=60, suite="stage-b-3-gpu-h200", labels=[]) +import sys from argparse import Namespace import diffusers @@ -91,3 +92,7 @@ def test_a_weight_sync_sends_the_heads_as_two_stacks_and_no_diffusers_name(lora_ assert sent_head_stacks.keys() == head_stacks.keys() for name, stack in head_stacks.items(): assert torch.equal(sent_head_stacks[name], stack), name + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v"])) From c31cf4dd5c5663c1de3056a54054a350c8841a6f Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:57:48 +0000 Subject: [PATCH 09/13] test(h3-image): reduce the head gradients under a bf16 forward too, where the heads are dtype overrides At fp32 the plan's fp32 patterns equal the default and compile to nothing, so the worker ran torch's stock reduce. A full-weight run forwards in bf16 by default: the heads, `proj_in` and the time embedder are then per-parameter overrides in the root wrap, which reduces through the patched mixed-dtype collectives. The test runs both. The worker compares in deterministic mode. The per-token AdaLN lookup repeats one timestep index and back-propagates as an index_add whose order on CUDA is not fixed; in bf16 that moved the time-embedding chain's gradients by about 1% between the wrapped model and the reference, while every other parameter was equal. The test puts the repository root on the worker's path itself, as test_reference_models does. --- .../_h3_image_head_gradients_worker.py | 34 +++++++++++++++---- .../test_h3_image_head_gradients.py | 22 ++++++++++-- 2 files changed, 47 insertions(+), 9 deletions(-) diff --git a/tests/fast-gpu/backends/fsdp_utils/_h3_image_head_gradients_worker.py b/tests/fast-gpu/backends/fsdp_utils/_h3_image_head_gradients_worker.py index 1a14f6b2d..4eb00cf1e 100644 --- a/tests/fast-gpu/backends/fsdp_utils/_h3_image_head_gradients_worker.py +++ b/tests/fast-gpu/backends/fsdp_utils/_h3_image_head_gradients_worker.py @@ -1,5 +1,6 @@ """Worker for test_h3_image_head_gradients: two ranks, each with a pair from another denoising step.""" +import argparse import os from argparse import Namespace @@ -16,6 +17,15 @@ STEP_BY_RANK = (0, 2) +def tiny_h3_image(forward_dtype: torch.dtype) -> torch.nn.Module: + """The tiny DiT with the weights a forward in ``forward_dtype`` runs: the release's fp32 modules stay fp32.""" + model = _tiny_h3_image().cuda() + for name, child in model.named_children(): + if name not in model._keep_in_fp32_modules: + child.to(forward_dtype) + return model + + def backward_through_step(model: torch.nn.Module, step: int) -> None: """One pair's loss through the head of ``step``; the pair itself is the same on every rank.""" visual, cond = _rows_and_cond(_t2i_layout()) @@ -35,38 +45,48 @@ def backward_through_step(model: torch.nn.Module, step: int) -> None: prediction.square().sum().backward() -def mean_gradients_of_the_ranks() -> dict[str, torch.Tensor]: - """What each parameter's gradient must reduce to: the mean of the ranks' own, zero where a rank has none.""" +def mean_gradients_of_the_ranks(forward_dtype: torch.dtype) -> dict[str, torch.Tensor]: + """What each parameter's gradient must reduce to: the fp32 mean of the ranks' own, zero where a rank has none.""" mean_gradients: dict[str, torch.Tensor] = {} for step in STEP_BY_RANK: - plain = _tiny_h3_image().cuda() + plain = tiny_h3_image(forward_dtype) backward_through_step(plain, step) for name, parameter in plain.named_parameters(): gradient = torch.zeros_like(parameter) if parameter.grad is None else parameter.grad - mean_gradients[name] = mean_gradients.get(name, 0) + gradient / len(STEP_BY_RANK) + mean_gradients[name] = mean_gradients.get(name, 0) + gradient.float() / len(STEP_BY_RANK) return mean_gradients def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--forward-dtype", choices=["fp32", "bf16"], required=True) + forward_dtype_name = parser.parse_args().forward_dtype + forward_dtype = {"fp32": torch.float32, "bf16": torch.bfloat16}[forward_dtype_name] + + # The per-token AdaLN lookup repeats one timestep index, so it back-propagates as an index_add, whose order on + # CUDA is not fixed: in bf16 that alone moves the time-embedding chain's gradients by about 1% between two runs. + torch.use_deterministic_algorithms(True) local_rank = int(os.environ["LOCAL_RANK"]) torch.cuda.set_device(local_rank) dist.init_process_group("nccl", device_id=torch.device("cuda", local_rank)) rank = dist.get_rank() assert dist.get_world_size() == len(STEP_BY_RANK) - # the same weights on every rank, wrapped and postprocessed as the loader does it + # the same fp32 master weights on every rank, wrapped with the family's plan and postprocessed as the loader + # does it. Under a bf16 forward the plan's fp32 modules, the heads among them, are per-parameter overrides, + # so their wrap reduces through the patched mixed-dtype collectives; under fp32 it is torch's stock reduce. model = _tiny_h3_image().cuda() train_pipeline_config = H3ImageTrainPipelineConfig() apply_fsdp2( model, DiffusersModelBackend(train_pipeline_config).fsdp_parallel_plan(model), - args=Namespace(diffusion_forward_dtype="fp32", fsdp_reduce_dtype="fp32"), + args=Namespace(diffusion_forward_dtype=forward_dtype_name, fsdp_reduce_dtype="fp32"), ) train_pipeline_config.postprocess_model_after_materialize(model) backward_through_step(model, STEP_BY_RANK[rank]) - mean_gradients = mean_gradients_of_the_ranks() + mean_gradients = mean_gradients_of_the_ranks(forward_dtype) for name, parameter in model.named_parameters(): gradient = parameter.grad assert gradient is not None, f"{name} has no gradient on rank {rank}" diff --git a/tests/fast-gpu/backends/fsdp_utils/test_h3_image_head_gradients.py b/tests/fast-gpu/backends/fsdp_utils/test_h3_image_head_gradients.py index ca6d2e0ef..150cfe6e3 100644 --- a/tests/fast-gpu/backends/fsdp_utils/test_h3_image_head_gradients.py +++ b/tests/fast-gpu/backends/fsdp_utils/test_h3_image_head_gradients.py @@ -26,11 +26,29 @@ @pytest.mark.skipif(torch.cuda.device_count() < 2, reason="Requires two CUDA devices") -def test_each_head_reduces_to_the_mean_of_its_own_gradients(): +@pytest.mark.parametrize("forward_dtype", ["fp32", "bf16"]) +def test_each_head_reduces_to_the_mean_of_its_own_gradients(forward_dtype): + """bf16 is a full-weight run's default forward: the heads stay fp32 there, and their wrap reduces through the + patched mixed-dtype collectives instead of torch's own.""" env = os.environ.copy() env["PYTHONUNBUFFERED"] = "1" + # cuBLAS needs this to run under torch.use_deterministic_algorithms, which the worker turns on. + env["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8" + # The worker imports the CPU test's tiny model from the `tests` package at the repository root. + repo_root = str(Path(__file__).resolve().parents[4]) + env["PYTHONPATH"] = os.pathsep.join(filter(None, [repo_root, env.get("PYTHONPATH")])) result = subprocess.run( - [sys.executable, "-m", "torch.distributed.run", "--standalone", "--nnodes=1", "--nproc_per_node=2", _WORKER], + [ + sys.executable, + "-m", + "torch.distributed.run", + "--standalone", + "--nnodes=1", + "--nproc_per_node=2", + _WORKER, + "--forward-dtype", + forward_dtype, + ], env=env, capture_output=True, text=True, From f7a7e34c947dc24f1769e3573ca4828230ed48ce Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:57:48 +0000 Subject: [PATCH 10/13] test(h3-image): one capturing updater for both sync modes, without the namespace field nothing reads --- .../fsdp_utils/test_h3_image_weight_sync.py | 30 ++++++++----------- 1 file changed, 13 insertions(+), 17 deletions(-) diff --git a/tests/fast-gpu/backends/fsdp_utils/test_h3_image_weight_sync.py b/tests/fast-gpu/backends/fsdp_utils/test_h3_image_weight_sync.py index 79c3db219..227778b16 100644 --- a/tests/fast-gpu/backends/fsdp_utils/test_h3_image_weight_sync.py +++ b/tests/fast-gpu/backends/fsdp_utils/test_h3_image_weight_sync.py @@ -26,22 +26,18 @@ ) -class _CaptureFullWeightUpdater(DiffusionUpdateWeightFromTensor): - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - self.buckets: list[list[tuple[str, torch.Tensor]]] = [] +def _capturing(updater_cls): + """``updater_cls`` with the buckets it would push to the rollout engine kept instead.""" - def update_bucket_weights(self, named_tensors, target_module): - self.buckets.append([(name, tensor.clone()) for name, tensor in named_tensors]) + class _CaptureUpdater(updater_cls): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.buckets: list[list[tuple[str, torch.Tensor]]] = [] + def update_bucket_weights(self, named_tensors, target_module): + self.buckets.append([(name, tensor.clone()) for name, tensor in named_tensors]) -class _CaptureMergedLoRAUpdater(DiffusionUpdateWeightFromTensorLoRA): - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - self.buckets: list[list[tuple[str, torch.Tensor]]] = [] - - def update_bucket_weights(self, named_tensors, target_module): - self.buckets.append([(name, tensor.clone()) for name, tensor in named_tensors]) + return _CaptureUpdater def _tiny_h3_image(): @@ -74,14 +70,14 @@ def test_a_weight_sync_sends_the_heads_as_two_stacks_and_no_diffusers_name(lora_ ) for suffix in ("weight", "bias") } - updater_cls = _CaptureFullWeightUpdater + updater_cls = DiffusionUpdateWeightFromTensor if lora_merged_in: model = get_peft_model(model, LoraConfig(r=4, lora_alpha=8, target_modules=["to_q", "to_k", "to_v"])) - updater_cls = _CaptureMergedLoRAUpdater + updater_cls = DiffusionUpdateWeightFromTensorLoRA # one byte: every tensor closes its bucket, so the held heads outlive the buckets they arrived in - args = Namespace(update_weight_buffer_size=1, train_pipeline_config_path=None, diffusion_model_family="h3_image") + args = Namespace(update_weight_buffer_size=1, diffusion_model_family="h3_image") - updater = updater_cls(args, {"transformer": model}) + updater = _capturing(updater_cls)(args, {"transformer": model}) updater.update_weights() sent = [(name, tensor) for bucket in updater.buckets for name, tensor in bucket] From e89bd002eaa9ac37741100c1051bdc28322a3849 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:26:57 +0000 Subject: [PATCH 11/13] test(h3-image): simulate an sglang without head updates on one that already has none, and let the dumped-rollouts case tell again - `monkeypatch.delattr` raised on an sglang-d from before the head update, before `validate_args` ran. - With a merged LoRA sync accepted, nothing refused the dumped-rollouts launch whether `train_only` was derived early or late. On an engine without head updates the family hook refuses it unless it reads `train_only` set. --- .../fast/backends/fsdp_utils/configs/test_h3_image.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/tests/fast/backends/fsdp_utils/configs/test_h3_image.py b/tests/fast/backends/fsdp_utils/configs/test_h3_image.py index 70abc55a9..cbe5e78e4 100644 --- a/tests/fast/backends/fsdp_utils/configs/test_h3_image.py +++ b/tests/fast/backends/fsdp_utils/configs/test_h3_image.py @@ -236,6 +236,11 @@ def test_supported_variations_are_accepted(overrides): H3ImageTrainPipelineConfig.validate_args(_grpo_args(**overrides)) +def _remove_head_updates_from_sglang(monkeypatch): + # raising=False: an sglang-d from before the head update has no constant to remove + monkeypatch.delattr(sglang_minimax_h3, "MINIMAX_H3_PDD_FUSED_HEADS_WEIGHT_NAME_PREFIX", raising=False) + + @pytest.mark.parametrize( ("overrides", "sync_sends_the_heads"), [ @@ -257,7 +262,7 @@ def test_supported_variations_are_accepted(overrides): ) def test_a_sync_that_sends_the_heads_needs_an_sglang_that_takes_them(monkeypatch, overrides, sync_sends_the_heads): """That engine skips the heads with a warning, and its rollouts keep the heads it started with.""" - monkeypatch.delattr(sglang_minimax_h3, "MINIMAX_H3_PDD_FUSED_HEADS_WEIGHT_NAME_PREFIX") + _remove_head_updates_from_sglang(monkeypatch) args = _grpo_args(**overrides) if sync_sends_the_heads: @@ -269,7 +274,7 @@ def test_a_sync_that_sends_the_heads_needs_an_sglang_that_takes_them(monkeypatch def test_a_config_named_by_path_is_refused_before_the_engine_is_asked_about_heads(monkeypatch): """Both ways out the head refusal names lead into this one, and by path no transform would send a stack.""" - monkeypatch.delattr(sglang_minimax_h3, "MINIMAX_H3_PDD_FUSED_HEADS_WEIGHT_NAME_PREFIX") + _remove_head_updates_from_sglang(monkeypatch) args = _grpo_args(use_lora=False, lora_ipc_weight_sync=False, diffusion_model_family=None) with pytest.raises(ValueError, match="cannot sync to a rollout engine"): @@ -308,6 +313,8 @@ def test_micro_batch_tiles_above_one_pair_are_rejected_through_the_parser(monkey def test_a_run_on_dumped_rollouts_is_not_held_to_a_sync_mode(monkeypatch): """--load-debug-rollout-data starts no engine, so there is no sync whose mode could be wrong.""" + # an engine that takes head updates refuses no sync mode, so only one that does not can tell + _remove_head_updates_from_sglang(monkeypatch) assert _validate_launch(monkeypatch, "--load-debug-rollout-data dump/{rollout_id}.pt").train_only From 5a799012dfffb0c86b7457daf3fb8efdf2a78a81 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:34:30 +0000 Subject: [PATCH 12/13] fix(h3-image): refuse full-weight training on a master dtype below fp32 at argument time Under `--fsdp-master-dtype bf16` diffusers still loads `proj_in`, the time embedder and the per-step heads in fp32. A LoRA trainer does not mind: only the adapters are trained. A full-weight trainer has both dtypes among the trained weights of the root wrap, and FSDP2 raises "expects uniform original parameter dtype" when the trainer is built, after every rank has loaded the DiT. Seen on 8 H200 with a bf16 master. --- miles/backends/fsdp_utils/configs/h3_image.py | 7 +++++++ .../backends/fsdp_utils/configs/test_h3_image.py | 12 ++++++++++++ 2 files changed, 19 insertions(+) diff --git a/miles/backends/fsdp_utils/configs/h3_image.py b/miles/backends/fsdp_utils/configs/h3_image.py index da9667af4..ed089a056 100644 --- a/miles/backends/fsdp_utils/configs/h3_image.py +++ b/miles/backends/fsdp_utils/configs/h3_image.py @@ -62,6 +62,13 @@ def validate_args(cls, args: Namespace) -> None: "with. Install an sglang-d that takes them, or train a LoRA and sync it as adapters (--use-lora, " "with --lora-ipc-weight-sync under --colocate)" ) + # diffusers loads proj_in, the time embedder and the per-step heads in fp32 under any master dtype + if not args.debug_rollout_only and not args.use_lora and args.fsdp_master_dtype != "fp32": + raise ValueError( + f"H3 Image trains all weights at --fsdp-master-dtype fp32 only, got {args.fsdp_master_dtype}: some " + "of its modules stay in fp32 under a lower master dtype, and FSDP refuses a wrap whose trained " + "weights differ in dtype. Use fp32, or train a LoRA (--use-lora)" + ) if args.diffusion_flow_shift is not None: raise ValueError("H3 Image samples on its release's sigma grid; drop --diffusion-flow-shift") if args.sequence_parallel_size != 1: diff --git a/tests/fast/backends/fsdp_utils/configs/test_h3_image.py b/tests/fast/backends/fsdp_utils/configs/test_h3_image.py index cbe5e78e4..bd16c0632 100644 --- a/tests/fast/backends/fsdp_utils/configs/test_h3_image.py +++ b/tests/fast/backends/fsdp_utils/configs/test_h3_image.py @@ -195,6 +195,7 @@ def _grpo_args(**overrides): micro_batch_size=1, diffusion_quality="exact", diffusion_true_cfg_scale=None, + fsdp_master_dtype="fp32", ) vars(args).update(overrides) return args @@ -220,6 +221,8 @@ def test_lora_flow_grpo_is_accepted(): {"diffusion_eval_num_steps": 6}, # a config named by path has no family key, which only a sync looks things up by {"diffusion_model_family": None, "train_only": True, "lora_ipc_weight_sync": False}, + # only the adapters are trained, and they share one dtype + {"fsdp_master_dtype": "bf16"}, ], ids=[ "rollout-only", @@ -230,6 +233,7 @@ def test_lora_flow_grpo_is_accepted(): "full-weight-train-only", "eval-steps-of-the-release", "config-by-path-train-only", + "lora-on-a-bf16-master", ], ) def test_supported_variations_are_accepted(overrides): @@ -347,6 +351,12 @@ def test_a_config_named_by_path_cannot_sync_to_an_engine(monkeypatch, sync_flags ({"diffusion_true_cfg_scale": 4.0}, "unguided"), # the forward raises on these at the first train step ({"micro_batch_size": 2}, "one pair"), + # FSDP refuses these when the trainer is built, after every rank has loaded the DiT + ({"use_lora": False, "lora_ipc_weight_sync": False, "fsdp_master_dtype": "bf16"}, "master-dtype fp32 only"), + ( + {"use_lora": False, "lora_ipc_weight_sync": False, "train_only": True, "fsdp_master_dtype": "bf16"}, + "master-dtype fp32 only", + ), ], ids=[ "nft", @@ -359,6 +369,8 @@ def test_a_config_named_by_path_cannot_sync_to_an_engine(monkeypatch, sync_flags "quality-high", "true-cfg", "micro-batch", + "full-weight-on-a-bf16-master", + "full-weight-train-only-on-a-bf16-master", ], ) def test_unsupported_training_settings_are_rejected(overrides, message): From b4cb67977e57d3e7ad6d31235a08765d37c6c255 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:47:28 +0000 Subject: [PATCH 13/13] test(h3-image): pin that a rollout-only run is exempt from the fp32 master rule and that fp16 is refused too --- tests/fast/backends/fsdp_utils/configs/test_h3_image.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/tests/fast/backends/fsdp_utils/configs/test_h3_image.py b/tests/fast/backends/fsdp_utils/configs/test_h3_image.py index bd16c0632..0c7dcd52c 100644 --- a/tests/fast/backends/fsdp_utils/configs/test_h3_image.py +++ b/tests/fast/backends/fsdp_utils/configs/test_h3_image.py @@ -223,6 +223,8 @@ def test_lora_flow_grpo_is_accepted(): {"diffusion_model_family": None, "train_only": True, "lora_ipc_weight_sync": False}, # only the adapters are trained, and they share one dtype {"fsdp_master_dtype": "bf16"}, + # no trainer is built + {"debug_rollout_only": True, "use_lora": False, "lora_ipc_weight_sync": False, "fsdp_master_dtype": "bf16"}, ], ids=[ "rollout-only", @@ -234,6 +236,7 @@ def test_lora_flow_grpo_is_accepted(): "eval-steps-of-the-release", "config-by-path-train-only", "lora-on-a-bf16-master", + "rollout-only-on-a-bf16-master", ], ) def test_supported_variations_are_accepted(overrides): @@ -354,7 +357,7 @@ def test_a_config_named_by_path_cannot_sync_to_an_engine(monkeypatch, sync_flags # FSDP refuses these when the trainer is built, after every rank has loaded the DiT ({"use_lora": False, "lora_ipc_weight_sync": False, "fsdp_master_dtype": "bf16"}, "master-dtype fp32 only"), ( - {"use_lora": False, "lora_ipc_weight_sync": False, "train_only": True, "fsdp_master_dtype": "bf16"}, + {"use_lora": False, "lora_ipc_weight_sync": False, "train_only": True, "fsdp_master_dtype": "fp16"}, "master-dtype fp32 only", ), ], @@ -370,7 +373,7 @@ def test_a_config_named_by_path_cannot_sync_to_an_engine(monkeypatch, sync_flags "true-cfg", "micro-batch", "full-weight-on-a-bf16-master", - "full-weight-train-only-on-a-bf16-master", + "full-weight-train-only-on-an-fp16-master", ], ) def test_unsupported_training_settings_are_rejected(overrides, message):