Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
35f0095
feat(h3-image): bridge a weight sync to the rollout's layout, the per…
zhihengy Nov 20, 2026
be24faf
fix(h3-image): give every per-step head a gradient on every rank
zhihengy Nov 20, 2026
8f6f815
feat(h3-image): accept full-weight training and merged LoRA syncs
zhihengy Nov 20, 2026
d3168ff
Merge h3-image/02-family into h3-image/04-full-weight
zhihengy Nov 20, 2026
566b535
fix(h3-image): refuse an engine without head updates as an argument e…
zhihengy Nov 20, 2026
bb33892
test(h3-image): reduce the two ranks' head gradients under the loader…
zhihengy Nov 20, 2026
a72ec8a
test(h3-image): send a tiny DiT through the updater, plain and with a…
zhihengy Nov 20, 2026
0599aaa
test(h3): the bridge is registered by adaptations' imports, no longer…
zhihengy Nov 20, 2026
0d15898
test(h3-image): give the weight sync test the entry point CI runs a G…
zhihengy Nov 20, 2026
945de13
Merge h3-image/02-family into h3-image/04-full-weight
zhihengy Nov 20, 2026
c31cf4d
test(h3-image): reduce the head gradients under a bf16 forward too, w…
zhihengy Nov 20, 2026
f7a7e34
test(h3-image): one capturing updater for both sync modes, without th…
zhihengy Nov 20, 2026
71cad8f
Merge h3-image/02-family into h3-image/04-full-weight
zhihengy Nov 20, 2026
e89bd00
test(h3-image): simulate an sglang without head updates on one that a…
zhihengy Nov 20, 2026
5a79901
fix(h3-image): refuse full-weight training on a master dtype below fp…
zhihengy Nov 20, 2026
b4cb679
test(h3-image): pin that a rollout-only run is exempt from the fp32 m…
zhihengy Nov 20, 2026
bed8b8d
Merge h3-image/02-family into h3-image/04-full-weight
zhihengy Nov 20, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions miles/backends/fsdp_utils/adaptations/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
56 changes: 42 additions & 14 deletions miles/backends/fsdp_utils/configs/h3_image.py
Original file line number Diff line number Diff line change
@@ -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

Expand All @@ -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."""
Expand All @@ -21,31 +38,36 @@ 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":
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:
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")
Expand Down Expand Up @@ -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,
*,
Expand Down
Original file line number Diff line number Diff line change
@@ -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)
110 changes: 110 additions & 0 deletions tests/fast-gpu/backends/fsdp_utils/_h3_image_head_gradients_worker.py
Original file line number Diff line number Diff line change
@@ -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()
62 changes: 62 additions & 0 deletions tests/fast-gpu/backends/fsdp_utils/test_h3_image_head_gradients.py
Original file line number Diff line number Diff line change
@@ -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"]))
Loading
Loading