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/configs/h3_image.py b/miles/backends/fsdp_utils/configs/h3_image.py index 1739308d1..ed089a056 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 @@ -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.""" @@ -21,6 +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 rollout_takes_pdd_fused_heads from miles.utils.arguments import rollout_merges_lora if args.loss_type != "policy_loss": @@ -28,24 +46,28 @@ 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 - syncs_weights_to_rollout = has_trainer and not args.train_only - if has_trainer and not args.use_lora: + syncs_weights_to_rollout = not args.debug_rollout_only and not args.train_only + if syncs_weights_to_rollout and args.diffusion_model_family != cls.model_family: 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" + "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 syncs_weights_to_rollout and not rollout_merges_lora(args): + # every sync but a LoRA adapter one carries the DiT's weights, its per-step output heads among them + if syncs_weights_to_rollout and not rollout_merges_lora(args) and not rollout_takes_pdd_fused_heads(): 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" + "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_weights_to_rollout and args.diffusion_model_family != cls.model_family: + # 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( - "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" + 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") @@ -87,6 +109,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/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..9eaccfd5c --- /dev/null +++ b/miles/backends/fsdp_utils/models/diffusers/h3_image/weight_bridge.py @@ -0,0 +1,54 @@ +"""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 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 ( # noqa: F401 + MINIMAX_H3_PDD_FUSED_HEADS_WEIGHT_NAME_PREFIX, + ) + except ImportError: + return False + return True + + +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] + # 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"{MINIMAX_H3_PDD_FUSED_HEADS_WEIGHT_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-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..4eb00cf1e --- /dev/null +++ b/tests/fast-gpu/backends/fsdp_utils/_h3_image_head_gradients_worker.py @@ -0,0 +1,110 @@ +"""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 + +import torch +import torch.distributed as dist +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 + +# 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(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()) + prediction = H3ImageTrainPipelineConfig().compute_noise_pred( + model=model, + 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, + 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(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(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.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 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=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(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}" + # 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(), + 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..150cfe6e3 --- /dev/null +++ b/tests/fast-gpu/backends/fsdp_utils/test_h3_image_head_gradients.py @@ -0,0 +1,62 @@ +"""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 +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") +@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, + "--forward-dtype", + forward_dtype, + ], + 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-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..227778b16 --- /dev/null +++ b/tests/fast-gpu/backends/fsdp_utils/test_h3_image_weight_sync.py @@ -0,0 +1,94 @@ +"""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=[]) + +import sys +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, +) + + +def _capturing(updater_cls): + """``updater_cls`` with the buckets it would push to the rollout engine kept instead.""" + + 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]) + + return _CaptureUpdater + + +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 = 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 = 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, diffusion_model_family="h3_image") + + updater = _capturing(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 + + +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 4269442dc..0c7dcd52c 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, ) @@ -155,6 +156,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", @@ -173,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 @@ -191,16 +214,80 @@ 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}, {"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"}, + # no trainer is built + {"debug_rollout_only": True, "use_lora": False, "lora_ipc_weight_sync": False, "fsdp_master_dtype": "bf16"}, + ], + ids=[ + "rollout-only", + "train-only", + "adapters-over-nccl", + "lora-synced-as-merged-weights", + "full-weight", + "full-weight-train-only", + "eval-steps-of-the-release", + "config-by-path-train-only", + "lora-on-a-bf16-master", + "rollout-only-on-a-bf16-master", ], - 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)) +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"), + [ + ({"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.""" + _remove_head_updates_from_sglang(monkeypatch) + args = _grpo_args(**overrides) + + if sync_sends_the_heads: + with pytest.raises(ValueError, match="does not take in a weight update"): + H3ImageTrainPipelineConfig.validate_args(args) + else: + H3ImageTrainPipelineConfig.validate_args(args) + + +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.""" + _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"): + H3ImageTrainPipelineConfig.validate_args(args) + + _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 " @@ -210,9 +297,10 @@ def test_supported_variations_are_accepted(overrides): ) -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) @@ -232,29 +320,28 @@ 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 -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) - - -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)) + _validate_launch(monkeypatch, sync_flags + path, use_lora=use_lora) @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"), @@ -267,10 +354,14 @@ 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"), + # 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": "fp16"}, + "master-dtype fp32 only", + ), ], ids=[ - "full-weight", - "lora-synced-as-merged-weights", "nft", "flow-shift", "sequence-parallel", @@ -281,6 +372,8 @@ def test_full_weight_training_is_rejected_even_without_an_engine(): "quality-high", "true-cfg", "micro-batch", + "full-weight-on-a-bf16-master", + "full-weight-train-only-on-an-fp16-master", ], ) def test_unsupported_training_settings_are_rejected(overrides, message): 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 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..7ba58beca --- /dev/null +++ b/tests/fast/backends/fsdp_utils/models/diffusers/h3_image/test_h3_image_weight_bridge.py @@ -0,0 +1,57 @@ +""" +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 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 + +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