diff --git a/docs/user-guide/cli-reference.md b/docs/user-guide/cli-reference.md index e249f433a..3cf3034e8 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. | @@ -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. | @@ -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 `/eval_/`, with an `index.jsonl` of prompts, seeds and rewards. Independent of `--wandb-log-num-images`. | -| `--load-debug-rollout-data` | path template | – | Replays a rollout with **no engines started**. | +| `--load-debug-rollout-data` | path template | – | Replays a rollout with **no engines started**; implies `--train-only`, also for the checks that refuse a setting only when an engine runs. | | `--load-debug-rollout-data-subsample` | float | – | | | `--save-debug-train-data` | path template | – | Fills `{rollout_id}` and `{rank}`. | | `--dump-details` | dir | – | Sets the debug dump paths for post-hoc analysis. | 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..1739308d1 --- /dev/null +++ b/miles/backends/fsdp_utils/configs/h3_image.py @@ -0,0 +1,145 @@ +"""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", "/h3_image") + # the release's sigma grid, one output head per step + num_denoising_steps = 6 + + @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 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 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 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 " + "--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: + 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" + ) + # 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" + ) + if args.diffusion_quality not in ("exact", "lossless"): + raise ValueError( + 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( + 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 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" + ) + step = int(denoising_step_indices.item()) + num_heads = len(model.pdd_proj_out) + # a negative step would index a head from the end + if not 0 <= step < num_heads: + raise ValueError( + f"denoising_step_index {step} is not one of H3 Image's {num_heads} per-step output heads " + f"(0..{num_heads - 1})" + ) + 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=step, + 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/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 new file mode 100644 index 000000000..4269442dc --- /dev/null +++ b/tests/fast/backends/fsdp_utils/configs/test_h3_image.py @@ -0,0 +1,300 @@ +"""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=[]) + +import shlex +import sys +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.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 +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(): + """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"): + _forward(_tiny_h3_image(), visual, cond, None) + + +@pytest.mark.parametrize("step", [-1, 3]) +def test_forward_rejects_a_step_without_an_output_head(step): + """The tiny model has heads 0..2; a step of -1 would otherwise run the last one.""" + visual, cond = _rows_and_cond(_t2i_layout()) + + with pytest.raises(ValueError, match="per-step output heads"): + _forward(_tiny_h3_image(), visual, cond, torch.tensor([step])) + + +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", + diffusion_model_family="h3_image", + use_lora=True, + 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, + diffusion_quality="exact", + diffusion_true_cfg_scale=None, + ) + vars(args).update(overrides) + return args + + +def test_lora_flow_grpo_is_accepted(): + H3ImageTrainPipelineConfig.validate_args(_grpo_args()) + + +@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}, + # engines on their own GPUs receive the adapters over NCCL + {"colocate": False, "lora_ipc_weight_sync": False}, + {"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", "eval-steps-of-the-release", "config-by-path-train-only"], +) +def test_supported_variations_are_accepted(overrides): + H3ImageTrainPipelineConfig.validate_args(_grpo_args(**overrides)) + + +_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" + + +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 + + +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"): + 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"), + # 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"), + ], + 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", + ], +) +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} + + pinned = compile_param_dtype_maps(model, [], patterns, torch.bfloat16).root_map + + assert fp32_names + 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 c3b77913e..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 @@ -43,6 +43,12 @@ 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"), + # 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): 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]} == { 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