From 2682ce5ac4ae9f0b69de29c3ed3635caffb5d4e0 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Tue, 17 Nov 2026 23:20:55 +0000 Subject: [PATCH 01/15] feat(h3-image): add the MiniMax H3 Image train family for t2i Flow-GRPO with LoRA The family key is `h3_image`; `MiniMaxAI/MiniMax-H3-Image` resolves to it over `h3` by the longer name pattern. Its forward runs `MiniMaxH3ImageTransformer2DModel` on the engine's packed t2i layout and selects the PDD output head by the pair's rollout step. It reuses H3's conditioning, FSDP dtype patterns and fused-qkv LoRA group. Argument validation refuses what cannot work yet: any loss but Flow-GRPO, any weight sync that sends the per-step heads, a flow shift, and trainer sequence parallelism. --- miles/backends/fsdp_utils/configs/h3_image.py | 95 +++++++++ .../models/diffusers/h3_image/__init__.py | 0 .../diffusers/h3_image/parallel_plan.py | 4 + .../hf_weight_iterator/atomic_groups.py | 6 +- .../fsdp_utils/configs/test_h3_image.py | 190 ++++++++++++++++++ .../test_train_pipeline_config_registry.py | 3 + .../test_lora_atomic_update_groups.py | 11 +- 7 files changed, 302 insertions(+), 7 deletions(-) create mode 100644 miles/backends/fsdp_utils/configs/h3_image.py create mode 100644 miles/backends/fsdp_utils/models/diffusers/h3_image/__init__.py create mode 100644 miles/backends/fsdp_utils/models/diffusers/h3_image/parallel_plan.py create mode 100644 tests/fast/backends/fsdp_utils/configs/test_h3_image.py diff --git a/miles/backends/fsdp_utils/configs/h3_image.py b/miles/backends/fsdp_utils/configs/h3_image.py new file mode 100644 index 000000000..11b5ddad9 --- /dev/null +++ b/miles/backends/fsdp_utils/configs/h3_image.py @@ -0,0 +1,95 @@ +"""MiniMax H3 Image: t2i Flow-GRPO on the release's PDD grid, LoRA only.""" + +from __future__ import annotations + +from argparse import Namespace + +import torch + +from .h3 import H3TrainPipelineConfig, _without_padding_tail +from .train_pipeline_config import register_train_pipeline_config + + +@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.""" + + tasks = ("t2i",) + hf_ckpt_name_patterns = ("minimax-h3-image", "minimax_h3_image", "/h3-image") + + @classmethod + def validate_args(cls, args: Namespace) -> None: + from miles.utils.arguments import rollout_merges_lora + + if args.loss_type != "policy_loss": + raise ValueError( + "H3 Image trains with --loss-type policy_loss only: its DiT picks an output head by the rollout's " + "denoising step, which no other loss provides" + ) + if not args.train_only and not rollout_merges_lora(args): + raise ValueError( + "H3 Image trains LoRA adapters and syncs them as adapters (--use-lora --lora-ipc-weight-sync): " + "every other sync sends the DiT's per-step output heads, which the rollout engine cannot receive" + ) + 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: + raise ValueError("H3 Image is untested with trainer sequence parallelism; set --sequence-parallel-size 1") + + @classmethod + def apply_rollout_sampling_params( + cls, + args: Namespace, + sampling_params: dict, + extra_sampling_params: dict, + ) -> None: + # 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 compute_noise_pred( + self, + *, + 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, + use_cfg: bool, + cfg_batching: bool, + guidance_scale: float, + true_cfg_scale: float | None, + ) -> dict[str, torch.Tensor]: + """Run the H3 Image forward on the target image rows, through the output head of the pair's rollout step.""" + del neg_cond, joint_cond, use_cfg, cfg_batching, guidance_scale, true_cfg_scale + if denoising_step_indices is None: + raise ValueError( + "H3 Image picks its output head by the rollout's denoising step, which this loss does not provide" + ) + cond = pos_cond + visual = latents_input["visual"] + device, dtype = visual.device, visual.dtype + if visual.shape[0] != 1: + raise NotImplementedError("H3 Image packed forward supports batch size 1 for now") + + layout = {k: (v.to(device) if isinstance(v, torch.Tensor) else v) for k, v in cond["h3_packed_layout"].items()} + token_tags, position_ids = _without_padding_tail(layout, torch.as_tensor(cond["h3_token_tags"], device=device)) + if not bool(layout["update_mask"].all()): + raise NotImplementedError("H3 Image trains t2i only; this layout carries reference image rows") + + out = model( + hidden_states=visual, + encoder_hidden_states=cond["encoder_hidden_states"].to(device=device, dtype=dtype), + # H3 time runs from t=0 noise to t=1 clean; every row of a t2i sequence is at the target's time + timestep=(1.0 - timesteps_input["visual"].float() / float(self.num_train_timesteps)).view(-1).to(dtype), + timestep_indices=torch.zeros(token_tags.shape[0], device=device, dtype=torch.long), + token_tags=token_tags.long(), + position_ids=position_ids.to(device=device, dtype=torch.float32), + image_indices=layout["img_pos"].view(-1).long(), + text_indices=layout["text_pos"].view(-1).long(), + pdd_step_index=int(denoising_step_indices.item()), + return_dict=False, + ) + # H3 predicts clean - noise; the shared flow objective predicts noise - clean. + return {"visual": (-out[0]).to(dtype)} diff --git a/miles/backends/fsdp_utils/models/diffusers/h3_image/__init__.py b/miles/backends/fsdp_utils/models/diffusers/h3_image/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/miles/backends/fsdp_utils/models/diffusers/h3_image/parallel_plan.py b/miles/backends/fsdp_utils/models/diffusers/h3_image/parallel_plan.py new file mode 100644 index 000000000..7cd8a6167 --- /dev/null +++ b/miles/backends/fsdp_utils/models/diffusers/h3_image/parallel_plan.py @@ -0,0 +1,4 @@ +# the H3 patterns cover H3 Image's fp32 modules: proj_in, time_embedder, pdd_proj_out +from miles.backends.fsdp_utils.models.diffusers.h3.parallel_plan import FSDP_PARALLEL_PLAN + +__all__ = ["FSDP_PARALLEL_PLAN"] diff --git a/miles/backends/training_utils/weight_update/hf_weight_iterator/atomic_groups.py b/miles/backends/training_utils/weight_update/hf_weight_iterator/atomic_groups.py index 9753238ee..069694d74 100644 --- a/miles/backends/training_utils/weight_update/hf_weight_iterator/atomic_groups.py +++ b/miles/backends/training_utils/weight_update/hf_weight_iterator/atomic_groups.py @@ -18,9 +18,9 @@ def get_hf_atomic_update_groups(diffusion_model_family: str | None) -> list[AtomicUpdateGroup]: - """Atomic groups for a diffusion model family. H3 fuses to_q/k/v into qkv_proj; Qwen-Image and Cosmos3 - fuse add_q/k/v_proj (into to_added_qkv / cross_attention.to_qkv).""" - if diffusion_model_family == "h3": + """Atomic groups for a diffusion model family. H3 and H3 Image fuse to_q/k/v into qkv_proj; Qwen-Image and + Cosmos3 fuse add_q/k/v_proj (into to_added_qkv / cross_attention.to_qkv).""" + if diffusion_model_family in ("h3", "h3_image"): return list(_H3_LORA_GROUPS) if diffusion_model_family in ("qwen_image", "cosmos3"): return list(_ADDED_QKV_LORA_GROUPS) diff --git a/tests/fast/backends/fsdp_utils/configs/test_h3_image.py b/tests/fast/backends/fsdp_utils/configs/test_h3_image.py new file mode 100644 index 000000000..9d16eed2f --- /dev/null +++ b/tests/fast/backends/fsdp_utils/configs/test_h3_image.py @@ -0,0 +1,190 @@ +"""MiniMax H3 Image train config: the forward reaches the output head of the pair's rollout step. + + rollout pair (step k, sigma_k) + sglang's packed t2i layout + -> MiniMaxH3ImageTransformer2DModel(..., timestep=1 - sigma_k, pdd_step_index=k) + -> negated: H3 predicts clean - noise, the flow objective noise - clean +""" + +from tests.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=20, suite="stage-a-cpu", labels=["fsdp"]) + +import fnmatch +from argparse import Namespace + +import diffusers +import pytest +import torch +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.packed_sequence import ( + minimax_h3_packed_sequence_ref2va_blocks, +) + +from miles.backends.fsdp_utils.configs.h3_image import H3ImageTrainPipelineConfig +from miles.backends.fsdp_utils.models.diffusers import load_fsdp_parallel_plan + +TEXT_LEN, LATENT_H, LATENT_W = 5, 8, 12 +NUM_IMAGE_ROWS = LATENT_H * LATENT_W // 4 +SIGMA = 0.75 + + +def _tiny_h3_image(forward_dtype=torch.float32): + with torch.random.fork_rng(): + torch.manual_seed(7) + model = 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, + ) + if forward_dtype == torch.bfloat16: + model.to(dtype=forward_dtype) + # the released checkpoint is mixed: these modules stay fp32 + for name, layer in model.named_modules(): + if any(fragment in name for fragment in model._keep_in_fp32_modules): + layer.float() + return model + + +def _t2i_layout(ref_blocks=()): + """The packed sequence the engine builds for one image: text rows, image rows, then a padding tail.""" + used_rows = TEXT_LEN + NUM_IMAGE_ROWS + sum(block["latent_h"] * block["latent_w"] // 4 for block in ref_blocks) + return 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=list(ref_blocks), + seq_len=((used_rows + 15) // 16) * 16 + 16, + ) + + +def _rows_and_cond(layout): + with torch.random.fork_rng(): + torch.manual_seed(11) + visual = torch.randn(1, NUM_IMAGE_ROWS, 96) + encoder_hidden_states = torch.randn(1, TEXT_LEN, 8) + cond = { + "encoder_hidden_states": encoder_hidden_states, + "h3_packed_layout": layout, + "h3_token_tags": layout["token_tags"], + } + return visual, cond + + +def _forward(model, visual, cond, denoising_step_indices): + return H3ImageTrainPipelineConfig().compute_noise_pred( + model=model, + latents_input={"visual": visual}, + timesteps_input={"visual": torch.tensor([SIGMA * 1000.0])}, + denoising_step_indices=denoising_step_indices, + pos_cond=cond, + neg_cond=None, + joint_cond=None, + use_cfg=False, + cfg_batching=False, + guidance_scale=1.0, + true_cfg_scale=None, + )["visual"] + + +@pytest.mark.parametrize("forward_dtype", [torch.float32, torch.bfloat16], ids=["fp32", "bf16"]) +def test_forward_runs_the_output_head_of_the_pairs_step(forward_dtype): + """Every head accepts every input, so a wrong head trains without an error.""" + model = _tiny_h3_image(forward_dtype) + layout = _t2i_layout() + visual, cond = _rows_and_cond(layout) + used_rows = int(layout["cu_seqlens"][1]) + + predictions = [_forward(model, visual, cond, torch.tensor([step])) for step in range(3)] + + for step, prediction in enumerate(predictions): + velocity = model( + hidden_states=visual, + encoder_hidden_states=cond["encoder_hidden_states"], + timestep=torch.tensor([1.0 - SIGMA]), + timestep_indices=torch.zeros(used_rows, dtype=torch.long), + token_tags=layout["token_tags"][:used_rows], + position_ids=layout["img_position_ids"][:used_rows].float(), + image_indices=layout["img_pos"], + text_indices=layout["text_pos"], + pdd_step_index=step, + return_dict=False, + )[0] + assert prediction.shape == (1, NUM_IMAGE_ROWS, 96) + assert torch.equal(prediction, -velocity.float()) + assert not torch.equal(predictions[0], predictions[2]) + + +def test_forward_without_the_rollout_step_is_rejected(): + """A loss that samples its own noise levels has no step to pick a head by.""" + visual, cond = _rows_and_cond(_t2i_layout()) + + with pytest.raises(ValueError, match="denoising step"): + _forward(_tiny_h3_image(), visual, cond, None) + + +def test_forward_rejects_a_layout_with_reference_rows(): + """An edit layout's image rows start with references, which are not target rows.""" + visual, cond = _rows_and_cond(_t2i_layout(ref_blocks=({"kind": "image", "latent_h": 4, "latent_w": 4},))) + + with pytest.raises(NotImplementedError, match="reference"): + _forward(_tiny_h3_image(), visual, cond, torch.tensor([0])) + + +def _grpo_args(**overrides): + args = Namespace( + loss_type="policy_loss", + use_lora=True, + lora_ipc_weight_sync=True, + colocate=True, + train_only=False, + diffusion_flow_shift=None, + sequence_parallel_size=1, + ) + vars(args).update(overrides) + return args + + +def test_lora_flow_grpo_is_accepted(): + H3ImageTrainPipelineConfig.validate_args(_grpo_args()) + + +@pytest.mark.parametrize( + ("overrides", "message"), + [ + ({"use_lora": False}, "LoRA"), + # merged base weights carry the per-step heads too + ({"lora_ipc_weight_sync": False}, "LoRA"), + ({"loss_type": "nft"}, "policy_loss"), + ({"diffusion_flow_shift": 3.0}, "flow-shift"), + ({"sequence_parallel_size": 2}, "sequence"), + ], + ids=["full-weight", "lora-synced-as-merged-weights", "nft", "flow-shift", "sequence-parallel"], +) +def test_unsupported_training_settings_are_rejected(overrides, message): + with pytest.raises(ValueError, match=message): + H3ImageTrainPipelineConfig.validate_args(_grpo_args(**overrides)) + + +def test_parallel_plan_keeps_the_fp32_modules_in_fp32(): + """The plan is H3's: a module H3 Image pins to fp32 under another name would be sharded as bf16.""" + patterns = load_fsdp_parallel_plan("h3_image").param_dtype_patterns + model = _tiny_h3_image() + fp32_names = [ + name for name, _ in model.named_parameters() if name.split(".")[0] in model._keep_in_fp32_modules + ] + + assert fp32_names + for name in fp32_names: + assert any(dtype == "fp32" and fnmatch.fnmatchcase(name, pattern) for pattern, dtype in patterns.items()), name 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 c3b77913e..e3034c004 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 @@ -43,6 +43,9 @@ class TestFamilyResolution: ("Wan-AI/Wan2.2-T2V-A14B", "wan2_2"), ("/data/ckpts/SD3.5-Medium-Finetune", "sd3"), ("krea/Krea-2-Raw", "krea2"), + ("MiniMaxAI/MiniMax-H3", "h3"), + # Longer pattern wins: "minimax-h3" is a substring of this id. + ("MiniMaxAI/MiniMax-H3-Image", "h3_image"), ], ) def test_known_patterns(self, ref, family): diff --git a/tests/fast/backends/training_utils/weight_update/hf_weight_iterator/test_lora_atomic_update_groups.py b/tests/fast/backends/training_utils/weight_update/hf_weight_iterator/test_lora_atomic_update_groups.py index c349ffb1c..e31756e9b 100644 --- a/tests/fast/backends/training_utils/weight_update/hf_weight_iterator/test_lora_atomic_update_groups.py +++ b/tests/fast/backends/training_utils/weight_update/hf_weight_iterator/test_lora_atomic_update_groups.py @@ -28,14 +28,17 @@ def _adapter_unit(module: str) -> list[tuple[str, torch.Tensor]]: return [(f"{module}.lora_A", torch.zeros(4, 8)), (f"{module}.lora_B", torch.zeros(8, 4))] -def _buckets(modules: list[str]) -> list[list[str]]: - units = assemble_atomic_update_groups(map(_adapter_unit, modules), get_hf_atomic_update_groups("h3")) +def _buckets(modules: list[str], family: str = "h3") -> list[list[str]]: + units = assemble_atomic_update_groups(map(_adapter_unit, modules), get_hf_atomic_update_groups(family)) return [[name for name, _ in bucket] for bucket in pack_units_by_size(units, max_bytes=1)] -def test_fused_qkv_adapters_share_one_bucket(): +@pytest.mark.parametrize("family", ["h3", "h3_image"]) +def test_fused_qkv_adapters_share_one_bucket(family): attention = "transformer_blocks.0.attn" - buckets = _buckets([f"{attention}.to_q", f"{attention}.to_k", f"{attention}.to_v", f"{attention}.to_out.0"]) + buckets = _buckets( + [f"{attention}.to_q", f"{attention}.to_k", f"{attention}.to_v", f"{attention}.to_out.0"], family + ) assert [len(bucket) for bucket in buckets] == [6, 2] assert {name.rsplit(".", 1)[0] for name in buckets[0]} == { From 29da8d1a175b4c6ac58416ed2d32b2ef2b24ed9e Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Wed, 18 Nov 2026 00:38:24 +0000 Subject: [PATCH 02/15] fix(h3-image): reject at argument time what the engine or the forward refuses The default --diffusion-num-steps 10 passed validation and failed at the first rollout with a 400 that the client retries for a minute, after both sides had loaded the DiT; a micro-batch above one failed at the first train step. The LoRA requirement now applies only to runs that sync weights, a local path spelled h3_image resolves to this family, and the plan test goes through compile_param_dtype_maps like H3's. The test file runs in the default CPU suite like its siblings. --- miles/backends/fsdp_utils/configs/h3_image.py | 30 +++++++++- .../fsdp_utils/configs/test_h3_image.py | 55 ++++++++++++++++--- .../test_train_pipeline_config_registry.py | 3 + 3 files changed, 78 insertions(+), 10 deletions(-) diff --git a/miles/backends/fsdp_utils/configs/h3_image.py b/miles/backends/fsdp_utils/configs/h3_image.py index 11b5ddad9..1cb254d01 100644 --- a/miles/backends/fsdp_utils/configs/h3_image.py +++ b/miles/backends/fsdp_utils/configs/h3_image.py @@ -15,7 +15,9 @@ class H3ImageTrainPipelineConfig(H3TrainPipelineConfig): """MiniMax H3 Image: the H3 DiT without audio rows, with one output head per denoising step.""" tasks = ("t2i",) - hf_ckpt_name_patterns = ("minimax-h3-image", "minimax_h3_image", "/h3-image") + hf_ckpt_name_patterns = ("minimax-h3-image", "minimax_h3_image", "/h3-image", "/h3_image") + # the release's sigma grid, one output head per step + num_denoising_steps = 6 @classmethod def validate_args(cls, args: Namespace) -> None: @@ -26,7 +28,8 @@ 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 loss provides" ) - if not args.train_only and not rollout_merges_lora(args): + syncs_weights_to_rollout = not args.train_only and not args.debug_rollout_only + if syncs_weights_to_rollout and not rollout_merges_lora(args): raise ValueError( "H3 Image trains LoRA adapters and syncs them as adapters (--use-lora --lora-ipc-weight-sync): " "every other sync sends the DiT's per-step output heads, which the rollout engine cannot receive" @@ -35,6 +38,29 @@ def validate_args(cls, args: Namespace) -> None: raise ValueError("H3 Image samples on its release's sigma grid; drop --diffusion-flow-shift") if args.sequence_parallel_size != 1: raise ValueError("H3 Image is untested with trainer sequence parallelism; set --sequence-parallel-size 1") + if args.diffusion_num_steps != cls.num_denoising_steps or args.diffusion_eval_num_steps not in ( + None, + cls.num_denoising_steps, + ): + raise ValueError( + f"H3 Image has one output head per step of its release's {cls.num_denoising_steps}-step grid; set " + f"--diffusion-num-steps {cls.num_denoising_steps} and drop --diffusion-eval-num-steps" + ) + if args.rollout_microgroup_size != 1 or args.diffusion_output_num_frames != 1: + raise ValueError( + "H3 Image rollout serves one image per request; keep --rollout-microgroup-size and " + "--diffusion-output-num-frames at 1" + ) + if (args.micro_batch_size, args.micro_batch_size_sample or 1, args.micro_batch_size_tstep or 1) != (1, 1, 1): + raise ValueError( + "H3 Image's packed forward takes one pair; keep --micro-batch-size, --micro-batch-size-sample and " + "--micro-batch-size-tstep at 1" + ) + if args.diffusion_quality == "high" or args.diffusion_true_cfg_scale not in (None, 1.0): + raise ValueError( + "H3 Image rollout serves --diffusion-quality exact or lossless, unguided; " + "drop --diffusion-true-cfg-scale" + ) @classmethod def apply_rollout_sampling_params( 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 9d16eed2f..9952569cf 100644 --- a/tests/fast/backends/fsdp_utils/configs/test_h3_image.py +++ b/tests/fast/backends/fsdp_utils/configs/test_h3_image.py @@ -7,9 +7,8 @@ from tests.ci.ci_register import register_cpu_ci -register_cpu_ci(est_time=20, suite="stage-a-cpu", labels=["fsdp"]) +register_cpu_ci(est_time=20, suite="stage-a-cpu", labels=[]) -import fnmatch from argparse import Namespace import diffusers @@ -20,6 +19,7 @@ ) from miles.backends.fsdp_utils.configs.h3_image import H3ImageTrainPipelineConfig +from miles.backends.fsdp_utils.mixed_precision import compile_param_dtype_maps from miles.backends.fsdp_utils.models.diffusers import load_fsdp_parallel_plan TEXT_LEN, LATENT_H, LATENT_W = 5, 8, 12 @@ -149,8 +149,18 @@ def _grpo_args(**overrides): lora_ipc_weight_sync=True, colocate=True, train_only=False, + debug_rollout_only=False, diffusion_flow_shift=None, sequence_parallel_size=1, + diffusion_num_steps=6, + diffusion_eval_num_steps=None, + rollout_microgroup_size=1, + diffusion_output_num_frames=1, + micro_batch_size=1, + micro_batch_size_sample=1, + micro_batch_size_tstep=1, + diffusion_quality="exact", + diffusion_true_cfg_scale=None, ) vars(args).update(overrides) return args @@ -160,6 +170,12 @@ def test_lora_flow_grpo_is_accepted(): H3ImageTrainPipelineConfig.validate_args(_grpo_args()) +@pytest.mark.parametrize("no_sync", ["train_only", "debug_rollout_only"]) +def test_a_run_that_syncs_no_weights_needs_no_lora(no_sync): + """The LoRA requirement is about what the engine can receive; a rollout-only smoke sends it nothing.""" + H3ImageTrainPipelineConfig.validate_args(_grpo_args(use_lora=False, lora_ipc_weight_sync=False, **{no_sync: True})) + + @pytest.mark.parametrize( ("overrides", "message"), [ @@ -169,8 +185,32 @@ def test_lora_flow_grpo_is_accepted(): ({"loss_type": "nft"}, "policy_loss"), ({"diffusion_flow_shift": 3.0}, "flow-shift"), ({"sequence_parallel_size": 2}, "sequence"), + # the engine answers each of these with a 400 after both sides have loaded the DiT + ({"diffusion_num_steps": 10}, "6-step grid"), + ({"diffusion_eval_num_steps": 40}, "6-step grid"), + ({"rollout_microgroup_size": 4}, "one image per request"), + ({"diffusion_output_num_frames": 5}, "one image per request"), + ({"diffusion_quality": "high"}, "exact or lossless"), + ({"diffusion_true_cfg_scale": 4.0}, "unguided"), + # the forward raises on these at the first train step + ({"micro_batch_size": 2}, "one pair"), + ({"micro_batch_size_tstep": 2}, "one pair"), + ], + ids=[ + "full-weight", + "lora-synced-as-merged-weights", + "nft", + "flow-shift", + "sequence-parallel", + "rollout-steps", + "eval-steps", + "microgroup", + "frames", + "quality-high", + "true-cfg", + "micro-batch", + "micro-batch-tstep", ], - ids=["full-weight", "lora-synced-as-merged-weights", "nft", "flow-shift", "sequence-parallel"], ) def test_unsupported_training_settings_are_rejected(overrides, message): with pytest.raises(ValueError, match=message): @@ -181,10 +221,9 @@ def test_parallel_plan_keeps_the_fp32_modules_in_fp32(): """The plan is H3's: a module H3 Image pins to fp32 under another name would be sharded as bf16.""" patterns = load_fsdp_parallel_plan("h3_image").param_dtype_patterns model = _tiny_h3_image() - fp32_names = [ - name for name, _ in model.named_parameters() if name.split(".")[0] in model._keep_in_fp32_modules - ] + fp32_names = {name for name, _ in model.named_parameters() if name.split(".")[0] in model._keep_in_fp32_modules} + + pinned = compile_param_dtype_maps(model, [], patterns, torch.bfloat16).root_map assert fp32_names - for name in fp32_names: - assert any(dtype == "fp32" and fnmatch.fnmatchcase(name, pattern) for pattern, dtype in patterns.items()), name + assert set(pinned) == fp32_names and set(pinned.values()) == {torch.float32} 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 e3034c004..4564b01ed 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 @@ -46,6 +46,9 @@ class TestFamilyResolution: ("MiniMaxAI/MiniMax-H3", "h3"), # Longer pattern wins: "minimax-h3" is a substring of this id. ("MiniMaxAI/MiniMax-H3-Image", "h3_image"), + # H3's "/h3" matches both local spellings too. + ("/data/ckpts/h3-image", "h3_image"), + ("/data/ckpts/h3_image", "h3_image"), ], ) def test_known_patterns(self, ref, family): From a5c672c66d1e2326e596f6937d636d8039e06cb5 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Wed, 18 Nov 2026 00:38:24 +0000 Subject: [PATCH 03/15] docs(h3-image): list the family in the CLI reference --- docs/user-guide/cli-reference.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/user-guide/cli-reference.md b/docs/user-guide/cli-reference.md index e249f433a..11358948a 100644 --- a/docs/user-guide/cli-reference.md +++ b/docs/user-guide/cli-reference.md @@ -174,8 +174,8 @@ See [Dtype Control](../advanced/dtype-control.md). | Flag | Type | Default | Notes | |---|---|---|---| | `--hf-checkpoint` | str | – | **Required.** Pipeline to train and to serve; also the family source. | -| `--diffusion-model-family` | str | – | Registered family key: `sd3`, `wan2_2`, `ltx`, `qwen_image`, `qwen_image21`, `cosmos3`, `krea2`, `h3`. Overrides name matching. The longest pattern wins, so `Qwen-Image-2.1` resolves to `qwen_image21`. | -| `--diffusion-task` | str | – | **Required** unless the config declares no `tasks`. The task to train, one of the family config's `tasks`: `t2i` (sd3, krea2, qwen_image, qwen_image21, cosmos3), `t2v` (wan2_2, ltx), `t2va` (h3, the only H3 rollout task) or `ref2va` (h3 joint video/audio SFT with ordered references on `transformer_ref`). | +| `--diffusion-model-family` | str | – | Registered family key: `sd3`, `wan2_2`, `ltx`, `qwen_image`, `qwen_image21`, `cosmos3`, `krea2`, `h3`, `h3_image`. Overrides name matching. The longest pattern wins, so `Qwen-Image-2.1` resolves to `qwen_image21`. | +| `--diffusion-task` | str | – | **Required** unless the config declares no `tasks`. The task to train, one of the family config's `tasks`: `t2i` (sd3, krea2, qwen_image, qwen_image21, cosmos3, h3_image), `t2v` (wan2_2, ltx), `t2va` (h3, the only H3 rollout task) or `ref2va` (h3 joint video/audio SFT with ordered references on `transformer_ref`). | | `--rollout-function-path` | str | `miles.rollout.sglang_rollout.generate_rollout` | Inherited Miles default; that module is not shipped in miles-diffusion, so set it — diffusion recipes pass `miles.rollout.sglang_diffusion_rollout.generate_rollout`. | | `--train-pipeline-config-path` | str | – | Your own `TrainPipelineConfig` for an unregistered family. Mutually exclusive with `--diffusion-model-family`. | | `--model-backend-path` | str | – | Override the family's model loader. | From 5b624900ad7a24975de7701f97a98d2d4c50a30c Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Wed, 18 Nov 2026 01:24:41 +0000 Subject: [PATCH 04/15] fix(h3-image): require LoRA whenever the trainer runs The LoRA check was skipped for --train-only, which syncs nothing but still trains: without --use-lora it would train all weights, the per-step output heads among them. LoRA is now required unless the run has no trainer (--debug-rollout-only); the adapter sync mode is required only of runs that sync. The sync error names the form each topology accepts. A parse-level test drives a launch through the real parser, whose defaults the hand-built namespace did not have. --- miles/backends/fsdp_utils/configs/h3_image.py | 14 +++-- .../fsdp_utils/configs/test_h3_image.py | 57 ++++++++++++++++--- 2 files changed, 59 insertions(+), 12 deletions(-) diff --git a/miles/backends/fsdp_utils/configs/h3_image.py b/miles/backends/fsdp_utils/configs/h3_image.py index 1cb254d01..1b4875582 100644 --- a/miles/backends/fsdp_utils/configs/h3_image.py +++ b/miles/backends/fsdp_utils/configs/h3_image.py @@ -28,11 +28,17 @@ 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 loss provides" ) - syncs_weights_to_rollout = not args.train_only and not args.debug_rollout_only - if syncs_weights_to_rollout and not rollout_merges_lora(args): + trains = not args.debug_rollout_only + if trains and not args.use_lora: raise ValueError( - "H3 Image trains LoRA adapters and syncs them as adapters (--use-lora --lora-ipc-weight-sync): " - "every other sync sends the DiT's per-step output heads, which the rollout engine cannot receive" + "H3 Image trains 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" + ) + if trains 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" ) 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/tests/fast/backends/fsdp_utils/configs/test_h3_image.py b/tests/fast/backends/fsdp_utils/configs/test_h3_image.py index 9952569cf..47f023613 100644 --- a/tests/fast/backends/fsdp_utils/configs/test_h3_image.py +++ b/tests/fast/backends/fsdp_utils/configs/test_h3_image.py @@ -9,6 +9,8 @@ register_cpu_ci(est_time=20, suite="stage-a-cpu", labels=[]) +import shlex +import sys from argparse import Namespace import diffusers @@ -18,9 +20,11 @@ minimax_h3_packed_sequence_ref2va_blocks, ) +from miles.backends.fsdp_utils.arguments import load_fsdp_args from miles.backends.fsdp_utils.configs.h3_image import H3ImageTrainPipelineConfig from miles.backends.fsdp_utils.mixed_precision import compile_param_dtype_maps from miles.backends.fsdp_utils.models.diffusers import load_fsdp_parallel_plan +from miles.utils.arguments import get_miles_extra_args_provider, miles_validate_args, set_default_diffusion_args TEXT_LEN, LATENT_H, LATENT_W = 5, 8, 12 NUM_IMAGE_ROWS = LATENT_H * LATENT_W // 4 @@ -157,8 +161,8 @@ def _grpo_args(**overrides): rollout_microgroup_size=1, diffusion_output_num_frames=1, micro_batch_size=1, - micro_batch_size_sample=1, - micro_batch_size_tstep=1, + micro_batch_size_sample=None, + micro_batch_size_tstep=None, diffusion_quality="exact", diffusion_true_cfg_scale=None, ) @@ -170,18 +174,55 @@ def test_lora_flow_grpo_is_accepted(): H3ImageTrainPipelineConfig.validate_args(_grpo_args()) -@pytest.mark.parametrize("no_sync", ["train_only", "debug_rollout_only"]) -def test_a_run_that_syncs_no_weights_needs_no_lora(no_sync): - """The LoRA requirement is about what the engine can receive; a rollout-only smoke sends it nothing.""" - H3ImageTrainPipelineConfig.validate_args(_grpo_args(use_lora=False, lora_ipc_weight_sync=False, **{no_sync: True})) +@pytest.mark.parametrize( + "overrides", + [ + # no trainer: nothing is trained and nothing is synced + {"debug_rollout_only": True, "use_lora": False, "lora_ipc_weight_sync": False}, + # a trainer without an engine: LoRA still, but no sync mode to hold it to + {"train_only": True, "lora_ipc_weight_sync": False, "colocate": 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", "one-pair-tiles", "eval-steps-of-the-release"], +) +def test_supported_variations_are_accepted(overrides): + H3ImageTrainPipelineConfig.validate_args(_grpo_args(**overrides)) + + +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 = ( + "test --hf-checkpoint MiniMaxAI/MiniMax-H3-Image --diffusion-task t2i --prompt-data prompts.jsonl " + "--rollout-function-path miles.rollout.sglang_diffusion_rollout.generate_rollout --rm-type ocr " + "--rollout-batch-size 8 --n-samples-per-prompt 16 --num-steps-per-rollout 2 --num-rollout 1 " + "--actor-num-gpus-per-node 8 --rollout-num-gpus 8 --rollout-num-gpus-per-engine 2 --colocate " + "--diffusion-num-steps 6 --diffusion-guidance-scale 1.0 --diffusion-sde-type cps " + "--use-lora --lora-ipc-weight-sync" + ) + monkeypatch.setattr(sys, "argv", shlex.split(argv)) + + args = load_fsdp_args(extra_args_provider=get_miles_extra_args_provider()) + set_default_diffusion_args(args) + miles_validate_args(args) + + assert args.diffusion_model_family == "h3_image" + 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"), + ({"use_lora": False}, "LoRA adapters only"), # merged base weights carry the per-step heads too - ({"lora_ipc_weight_sync": False}, "LoRA"), + ({"lora_ipc_weight_sync": False}, "as adapters"), ({"loss_type": "nft"}, "policy_loss"), ({"diffusion_flow_shift": 3.0}, "flow-shift"), ({"sequence_parallel_size": 2}, "sequence"), From 958db5a20737e0388e6eeaa9ac3677b8229677b3 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Wed, 18 Nov 2026 01:36:35 +0000 Subject: [PATCH 05/15] fix(h3-image): check the folded micro-batch size and word the loss and LoRA errors as what they reject The family re-derived the sample x timestep tiles that miles_validate_args has already folded into micro_batch_size, and one test pinned a namespace the parser cannot produce. The loss error claimed no other loss sets the step, which custom_loss can; the LoRA error spoke of training for a run that only has a trainer. Adapters over NCCL, the form non-colocated and async runs use, get an accepted case. --- miles/backends/fsdp_utils/configs/h3_image.py | 15 ++++++++------- .../backends/fsdp_utils/configs/test_h3_image.py | 9 ++++++--- 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/miles/backends/fsdp_utils/configs/h3_image.py b/miles/backends/fsdp_utils/configs/h3_image.py index 1b4875582..ec0c7aa89 100644 --- a/miles/backends/fsdp_utils/configs/h3_image.py +++ b/miles/backends/fsdp_utils/configs/h3_image.py @@ -26,15 +26,15 @@ def validate_args(cls, args: Namespace) -> None: if args.loss_type != "policy_loss": raise ValueError( "H3 Image trains with --loss-type policy_loss only: its DiT picks an output head by the rollout's " - "denoising step, which no other loss provides" + "denoising step, which no other built-in loss sets, and custom_loss is untested" ) - trains = not args.debug_rollout_only - if trains and not args.use_lora: + has_trainer = not args.debug_rollout_only + if has_trainer and not args.use_lora: raise ValueError( - "H3 Image trains 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" + "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" ) - if trains and not args.train_only and not rollout_merges_lora(args): + 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 " @@ -57,7 +57,8 @@ def validate_args(cls, args: Namespace) -> None: "H3 Image rollout serves one image per request; keep --rollout-microgroup-size and " "--diffusion-output-num-frames at 1" ) - if (args.micro_batch_size, args.micro_batch_size_sample or 1, args.micro_batch_size_tstep or 1) != (1, 1, 1): + # miles_validate_args has folded the sample x timestep tiles into micro_batch_size + if args.micro_batch_size != 1: raise ValueError( "H3 Image's packed forward takes one pair; keep --micro-batch-size, --micro-batch-size-sample and " "--micro-batch-size-tstep at 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 47f023613..5a3a5d7ff 100644 --- a/tests/fast/backends/fsdp_utils/configs/test_h3_image.py +++ b/tests/fast/backends/fsdp_utils/configs/test_h3_image.py @@ -181,11 +181,13 @@ def test_lora_flow_grpo_is_accepted(): {"debug_rollout_only": True, "use_lora": False, "lora_ipc_weight_sync": False}, # a trainer without an engine: LoRA still, but no sync mode to hold it to {"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}, # 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", "one-pair-tiles", "eval-steps-of-the-release"], + ids=["rollout-only", "train-only", "adapters-over-nccl", "one-pair-tiles", "eval-steps-of-the-release"], ) def test_supported_variations_are_accepted(overrides): H3ImageTrainPipelineConfig.validate_args(_grpo_args(**overrides)) @@ -235,7 +237,8 @@ def test_full_weight_training_is_rejected_even_without_an_engine(): ({"diffusion_true_cfg_scale": 4.0}, "unguided"), # the forward raises on these at the first train step ({"micro_batch_size": 2}, "one pair"), - ({"micro_batch_size_tstep": 2}, "one pair"), + # the parser folds the tiles into micro_batch_size + ({"micro_batch_size": 2, "micro_batch_size_sample": 2, "micro_batch_size_tstep": 1}, "one pair"), ], ids=[ "full-weight", @@ -250,7 +253,7 @@ def test_full_weight_training_is_rejected_even_without_an_engine(): "quality-high", "true-cfg", "micro-batch", - "micro-batch-tstep", + "micro-batch-tiles", ], ) def test_unsupported_training_settings_are_rejected(overrides, message): From af1ac5a70546c9b883360dabd1f0a75c9b342a5f Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:19:40 +0000 Subject: [PATCH 06/15] fix(args): derive train_only from --load-debug-rollout-data before the checks that read it `miles_validate_args` set `train_only` for a run on dumped rollouts near its end, after the family hook, the LoRA sync check and the sft check had read it. Such a run starts no engine, yet H3 Image refused it for the sync mode of its LoRA. --- miles/utils/arguments.py | 15 ++++---- .../fsdp_utils/configs/test_h3_image.py | 34 ++++++++++++------- 2 files changed, 29 insertions(+), 20 deletions(-) diff --git a/miles/utils/arguments.py b/miles/utils/arguments.py index d943d311c..a0df6d645 100644 --- a/miles/utils/arguments.py +++ b/miles/utils/arguments.py @@ -2065,6 +2065,14 @@ def validate_dmd2_args(args) -> None: def miles_validate_args(args): + # before the checks below that read train_only + if args.load_debug_rollout_data is not None: + logger.info( + f"load_debug_rollout_data {args.load_debug_rollout_data} is set, " + "will not instantiate sglang servers and will only run the training process." + ) + args.train_only = True + args.eval_datasets = _resolve_eval_datasets(args) if args.eval_interval is not None: @@ -2257,13 +2265,6 @@ def miles_validate_args(args): args.save_debug_rollout_data = f"{args.dump_details}/rollout_data/{{rollout_id}}.pt" args.save_debug_train_data = f"{args.dump_details}/train_data/{{rollout_id}}_{{rank}}.pt" - if args.load_debug_rollout_data is not None: - logger.info( - f"load_debug_rollout_data {args.load_debug_rollout_data} is set, " - "will not instantiate sglang servers and will only run the training process." - ) - args.train_only = True - validate_output_store_args(args) if args.offload: 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..f9f6b3ec0 100644 --- a/tests/fast/backends/fsdp_utils/configs/test_h3_image.py +++ b/tests/fast/backends/fsdp_utils/configs/test_h3_image.py @@ -193,24 +193,32 @@ def test_supported_variations_are_accepted(overrides): H3ImageTrainPipelineConfig.validate_args(_grpo_args(**overrides)) -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 = ( - "test --hf-checkpoint MiniMaxAI/MiniMax-H3-Image --diffusion-task t2i --prompt-data prompts.jsonl " - "--rollout-function-path miles.rollout.sglang_diffusion_rollout.generate_rollout --rm-type ocr " - "--rollout-batch-size 8 --n-samples-per-prompt 16 --num-steps-per-rollout 2 --num-rollout 1 " - "--actor-num-gpus-per-node 8 --rollout-num-gpus 8 --rollout-num-gpus-per-engine 2 --colocate " - "--diffusion-num-steps 6 --diffusion-guidance-scale 1.0 --diffusion-sde-type cps " - "--use-lora --lora-ipc-weight-sync" - ) - monkeypatch.setattr(sys, "argv", shlex.split(argv)) +_LAUNCH = ( + "test --hf-checkpoint MiniMaxAI/MiniMax-H3-Image --diffusion-task t2i --prompt-data prompts.jsonl " + "--rollout-function-path miles.rollout.sglang_diffusion_rollout.generate_rollout --rm-type ocr " + "--rollout-batch-size 8 --n-samples-per-prompt 16 --num-steps-per-rollout 2 --num-rollout 1 " + "--actor-num-gpus-per-node 8 --rollout-num-gpus 8 --rollout-num-gpus-per-engine 2 --colocate " + "--diffusion-num-steps 6 --diffusion-guidance-scale 1.0 --diffusion-sde-type cps --use-lora " +) + +def _validate_launch(monkeypatch, flags): + """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)) args = load_fsdp_args(extra_args_provider=get_miles_extra_args_provider()) set_default_diffusion_args(args) miles_validate_args(args) + return 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.""" + assert _validate_launch(monkeypatch, "--lora-ipc-weight-sync").diffusion_model_family == "h3_image" + - assert args.diffusion_model_family == "h3_image" - assert (args.micro_batch_size_sample, args.micro_batch_size_tstep) == (None, None) +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.""" + assert _validate_launch(monkeypatch, "--load-debug-rollout-data dump/{rollout_id}.pt").train_only def test_full_weight_training_is_rejected_even_without_an_engine(): From 29191e502fb148e26f24184bd85f8959c1b053b8 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:19:41 +0000 Subject: [PATCH 07/15] fix(h3-image): refuse a config named by path for a run that syncs to an engine `--train-pipeline-config-path` leaves `--diffusion-model-family` unset, and the fused-qkv LoRA group is looked up by that key: the adapters of to_q, to_k and to_v could reach the engine in different buckets, and its merge replaces a fused layer's LoRA with the sections one request carries. The lookup by a second key is on main for every family; here the run is refused by name until the group follows the config class. --- miles/backends/fsdp_utils/configs/h3_image.py | 6 ++++++ .../fsdp_utils/configs/test_h3_image.py | 20 ++++++++++++++++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/miles/backends/fsdp_utils/configs/h3_image.py b/miles/backends/fsdp_utils/configs/h3_image.py index ec0c7aa89..931cc3a19 100644 --- a/miles/backends/fsdp_utils/configs/h3_image.py +++ b/miles/backends/fsdp_utils/configs/h3_image.py @@ -40,6 +40,12 @@ def validate_args(cls, args: Namespace) -> None: "otherwise): a merged sync sends the DiT's per-step output heads, which the rollout engine cannot " "receive" ) + if has_trainer and not args.train_only 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" + ) 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 f9f6b3ec0..d5c9a85f9 100644 --- a/tests/fast/backends/fsdp_utils/configs/test_h3_image.py +++ b/tests/fast/backends/fsdp_utils/configs/test_h3_image.py @@ -149,6 +149,7 @@ def test_forward_rejects_a_layout_with_reference_rows(): def _grpo_args(**overrides): args = Namespace( loss_type="policy_loss", + diffusion_model_family="h3_image", use_lora=True, lora_ipc_weight_sync=True, colocate=True, @@ -186,8 +187,17 @@ def test_lora_flow_grpo_is_accepted(): # the recipe's explicit one-pair tiles {"micro_batch_size_sample": 1, "micro_batch_size_tstep": 1}, {"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}, + ], + ids=[ + "rollout-only", + "train-only", + "adapters-over-nccl", + "one-pair-tiles", + "eval-steps-of-the-release", + "config-by-path-train-only", ], - ids=["rollout-only", "train-only", "adapters-over-nccl", "one-pair-tiles", "eval-steps-of-the-release"], ) def test_supported_variations_are_accepted(overrides): H3ImageTrainPipelineConfig.validate_args(_grpo_args(**overrides)) @@ -221,6 +231,14 @@ 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" + + with pytest.raises(ValueError, match="cannot sync to a rollout engine"): + _validate_launch(monkeypatch, path_flags) + + 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"): From 5b8b83fe3149c22c1ce836191ac8c6a1760ec69a Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:19:41 +0000 Subject: [PATCH 08/15] fix(h3-image): give the quality and the guidance refusals their own conditions `--diffusion-quality high` alone was told to drop `--diffusion-true-cfg-scale`, and the condition named the one level the engine refuses instead of the two it serves. --- miles/backends/fsdp_utils/configs/h3_image.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/miles/backends/fsdp_utils/configs/h3_image.py b/miles/backends/fsdp_utils/configs/h3_image.py index 931cc3a19..b4950c9a9 100644 --- a/miles/backends/fsdp_utils/configs/h3_image.py +++ b/miles/backends/fsdp_utils/configs/h3_image.py @@ -69,11 +69,12 @@ def validate_args(cls, args: Namespace) -> None: "H3 Image's packed forward takes one pair; keep --micro-batch-size, --micro-batch-size-sample and " "--micro-batch-size-tstep at 1" ) - if args.diffusion_quality == "high" or args.diffusion_true_cfg_scale not in (None, 1.0): + if args.diffusion_quality not in ("exact", "lossless"): raise ValueError( - "H3 Image rollout serves --diffusion-quality exact or lossless, unguided; " - "drop --diffusion-true-cfg-scale" + f"H3 Image rollout serves --diffusion-quality exact or lossless, got {args.diffusion_quality!r}" ) + if args.diffusion_true_cfg_scale not in (None, 1.0): + raise ValueError("H3 Image rollout is unguided; drop --diffusion-true-cfg-scale") @classmethod def apply_rollout_sampling_params( From a287c1d11d72f53229ee6ce5bed85924b1a1af23 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:19:41 +0000 Subject: [PATCH 09/15] test(h3-image): check the micro-batch tiles through the parser `validate_args` reads only `micro_batch_size`, which the parser folds the tiles into before the family hook runs. The cases that set the tile fields on a hand-built namespace read nothing; one launch line through the parser pins the fold order instead. --- .../fsdp_utils/configs/test_h3_image.py | 22 ++++++------------- 1 file changed, 7 insertions(+), 15 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 d5c9a85f9..44abd304d 100644 --- a/tests/fast/backends/fsdp_utils/configs/test_h3_image.py +++ b/tests/fast/backends/fsdp_utils/configs/test_h3_image.py @@ -162,8 +162,6 @@ def _grpo_args(**overrides): rollout_microgroup_size=1, diffusion_output_num_frames=1, micro_batch_size=1, - micro_batch_size_sample=None, - micro_batch_size_tstep=None, diffusion_quality="exact", diffusion_true_cfg_scale=None, ) @@ -184,20 +182,11 @@ 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}, - # the recipe's explicit one-pair tiles - {"micro_batch_size_sample": 1, "micro_batch_size_tstep": 1}, {"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}, ], - ids=[ - "rollout-only", - "train-only", - "adapters-over-nccl", - "one-pair-tiles", - "eval-steps-of-the-release", - "config-by-path-train-only", - ], + ids=["rollout-only", "train-only", "adapters-over-nccl", "eval-steps-of-the-release", "config-by-path-train-only"], ) def test_supported_variations_are_accepted(overrides): H3ImageTrainPipelineConfig.validate_args(_grpo_args(**overrides)) @@ -226,6 +215,12 @@ def test_a_launch_with_the_required_flags_passes_the_real_parser(monkeypatch): assert _validate_launch(monkeypatch, "--lora-ipc-weight-sync").diffusion_model_family == "h3_image" +def test_micro_batch_tiles_above_one_pair_are_rejected_through_the_parser(monkeypatch): + """The check reads micro_batch_size, which the parser folds the tiles into before the family hook runs.""" + with pytest.raises(ValueError, match="one pair"): + _validate_launch(monkeypatch, "--lora-ipc-weight-sync --micro-batch-size-sample 2 --micro-batch-size-tstep 1") + + 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.""" assert _validate_launch(monkeypatch, "--load-debug-rollout-data dump/{rollout_id}.pt").train_only @@ -263,8 +258,6 @@ def test_full_weight_training_is_rejected_even_without_an_engine(): ({"diffusion_true_cfg_scale": 4.0}, "unguided"), # the forward raises on these at the first train step ({"micro_batch_size": 2}, "one pair"), - # the parser folds the tiles into micro_batch_size - ({"micro_batch_size": 2, "micro_batch_size_sample": 2, "micro_batch_size_tstep": 1}, "one pair"), ], ids=[ "full-weight", @@ -279,7 +272,6 @@ def test_full_weight_training_is_rejected_even_without_an_engine(): "quality-high", "true-cfg", "micro-batch", - "micro-batch-tiles", ], ) def test_unsupported_training_settings_are_rejected(overrides, message): From 6f098bb71af87fdf0e2f8647566f697b7850f16c Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:19:41 +0000 Subject: [PATCH 10/15] docs(cli): say the H3 rollout flags are family h3's alone --- docs/user-guide/cli-reference.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/user-guide/cli-reference.md b/docs/user-guide/cli-reference.md index 11358948a..295d174fb 100644 --- a/docs/user-guide/cli-reference.md +++ b/docs/user-guide/cli-reference.md @@ -192,9 +192,9 @@ See [Dtype Control](../advanced/dtype-control.md). | `--diffusion-noise-level` | float | `0.7` | | | `--diffusion-quality` | enum | `exact` | `exact` / `lossless` / `high`: sglang-diffusion request quality level. `exact` is the bit-identical reference path; the looser levels mount rounding-changing fusions. | | `--diffusion-height` / `--diffusion-width` | int | `512` | Rollout output size; SFT target media must already be this size. | -| `--diffusion-h3-aspect-ratio` | str | `16:9` | MiniMax H3 only: `21:9` / `16:9` / `4:3` / `1:1` / `3:4` / `9:16`. | -| `--diffusion-h3-duration-seconds` | float | `5.0` | MiniMax H3 only: rollout duration, 4.0–15.0 s. | -| `--diffusion-audio-flow-shift` | float | `3.0` | MiniMax H3 only: audio flow shift for rollout. | +| `--diffusion-h3-aspect-ratio` | str | `16:9` | Family `h3` only (`h3_image` takes its canvas from `--diffusion-width` / `--diffusion-height`): `21:9` / `16:9` / `4:3` / `1:1` / `3:4` / `9:16`. | +| `--diffusion-h3-duration-seconds` | float | `5.0` | Family `h3` only: rollout duration, 4.0–15.0 s. | +| `--diffusion-audio-flow-shift` | float | `3.0` | Family `h3` only: audio flow shift for rollout. | | `--diffusion-sde-type` | str | `sde` | `sde` / `cps` / `ode`, checked at startup unless `--sde-step-backend-path` is set. Selects the train-side SDE backend too. | | `--sde-step-backend-path` | str | – | Custom dynamics. See [SDE backends](#sde-step-backends). | | `--diffusion-num-sde-steps` | int | `0` | Read by the step strategy. | From e6961ad4b26bf2eb675bddbaaf3d59549f6a8017 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:52:44 +0000 Subject: [PATCH 11/15] test(args): pin the early train_only derivation without a model family The only test of the move went through H3 Image's refusal of a merged LoRA sync, which #410 relaxes. A run on dumped rollouts with `--lora-ipc-weight-sync` and no `--colocate` is refused by the shared LoRA sync check when `train_only` is derived after it. --- tests/fast/utils/test_loss_type_recipes_parse.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/tests/fast/utils/test_loss_type_recipes_parse.py b/tests/fast/utils/test_loss_type_recipes_parse.py index cf8164ea8..8101694f2 100644 --- a/tests/fast/utils/test_loss_type_recipes_parse.py +++ b/tests/fast/utils/test_loss_type_recipes_parse.py @@ -103,3 +103,14 @@ def test_dmd2_trainer_groups_get_their_hooks_by_role(parse): def test_a_hook_path_outside_custom_loss_fails_validation(parse): with pytest.raises(ValueError, match="read only under --loss-type custom_loss"): parse(ARGV_BY_LOSS_TYPE["nft"] + " --teacher-load teacher --custom-loss-function-path my.formula") + + +def test_a_run_on_dumped_rollouts_counts_as_train_only_for_every_check(parse): + """--load-debug-rollout-data starts no engine: a check that reads train_only before it is derived refuses the + run for an engine it does not have.""" + args = parse( + ARGV_BY_LOSS_TYPE["policy_loss"] + + " --use-lora --lora-target-modules to_q --lora-ipc-weight-sync --load-debug-rollout-data dump/{rollout_id}.pt" + ) + + assert args.train_only From 8045752c1634630ea9694df8cef4b531c6f0b54f Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:52:44 +0000 Subject: [PATCH 12/15] fix(h3-image): say what a forward without the denoising step is missing The error blamed the loss, which `validate_args` already restricts to policy_loss. Since the prepare hook takes pairs without `denoising_step_index`, the forward sees None only when an expander did not set the key. --- miles/backends/fsdp_utils/configs/h3_image.py | 3 ++- tests/fast/backends/fsdp_utils/configs/test_h3_image.py | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/miles/backends/fsdp_utils/configs/h3_image.py b/miles/backends/fsdp_utils/configs/h3_image.py index b4950c9a9..8912ed786 100644 --- a/miles/backends/fsdp_utils/configs/h3_image.py +++ b/miles/backends/fsdp_utils/configs/h3_image.py @@ -105,7 +105,8 @@ def compute_noise_pred( del neg_cond, joint_cond, use_cfg, cfg_batching, guidance_scale, true_cfg_scale if denoising_step_indices is None: raise ValueError( - "H3 Image picks its output head by the rollout's denoising step, which this loss does not provide" + "H3 Image picks its output head by each pair's denoising step, which these pairs do not carry: " + "an expander that feeds Flow-GRPO must set denoising_step_index on every pair" ) cond = pos_cond visual = latents_input["visual"] 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 44abd304d..0667633df 100644 --- a/tests/fast/backends/fsdp_utils/configs/test_h3_image.py +++ b/tests/fast/backends/fsdp_utils/configs/test_h3_image.py @@ -131,7 +131,7 @@ def test_forward_runs_the_output_head_of_the_pairs_step(forward_dtype): def test_forward_without_the_rollout_step_is_rejected(): - """A loss that samples its own noise levels has no step to pick a head by.""" + """Pairs from an expander that records no step leave the forward no head to pick.""" visual, cond = _rows_and_cond(_t2i_layout()) with pytest.raises(ValueError, match="denoising step"): From 64eb077094958df0e15363c084e03d03a74f3042 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:52:44 +0000 Subject: [PATCH 13/15] refactor(h3-image): name once the condition under which the run syncs weights to an engine --- miles/backends/fsdp_utils/configs/h3_image.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/miles/backends/fsdp_utils/configs/h3_image.py b/miles/backends/fsdp_utils/configs/h3_image.py index 8912ed786..31c678685 100644 --- a/miles/backends/fsdp_utils/configs/h3_image.py +++ b/miles/backends/fsdp_utils/configs/h3_image.py @@ -29,18 +29,19 @@ 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 + syncs_weights_to_rollout = has_trainer and not args.train_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" ) - if has_trainer and not args.train_only and not rollout_merges_lora(args): + if syncs_weights_to_rollout 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" ) - if has_trainer and not args.train_only and args.diffusion_model_family != cls.model_family: + if syncs_weights_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 " From a427d1ed9f97c1d98e00b0947bdc619527a3e42f Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:52:44 +0000 Subject: [PATCH 14/15] docs(cli): --load-debug-rollout-data implies --train-only --- docs/user-guide/cli-reference.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/user-guide/cli-reference.md b/docs/user-guide/cli-reference.md index 295d174fb..3cf3034e8 100644 --- a/docs/user-guide/cli-reference.md +++ b/docs/user-guide/cli-reference.md @@ -409,7 +409,7 @@ Every one takes a dotted path. | `--debug-skip-optimizer-step` | flag | off | No backward/step — weights never drift. Use it to measure pure forward divergence from the engine. | | `--save-debug-rollout-data` | path template | – | Fills `{rollout_id}`. | | `--save-eval-media-dir` | path | – | Keeps every eval sample's video (with its audio when the engine returns it) or image under `