akhaliq's picture
akhaliq HF Staff
merge/: assign=True in control load (meta-device safe)
65ba063 verified
Raw History Blame Contribute Delete
17.1 kB
"""Validate: attach MiniMax-H3-Fun-Controlnet-Union-2.0 (video-trained control branch)
to the diffusers MiniMaxH3ImageTransformer2DModel from MiniMaxAI/MiniMax-H3-Image.
Checks (fixed seed, same prompt):
1. control_rows=None base generation (t2i_base.png)
2. control rows attached, scale 0.0 -> must be near-identical to base (PSNR > 40 dB)
3. canny-edge control at scale 0.5 and 1.0 -> structure should steer (low PSNR vs base)
Run on H200. Needs: diffusers>=0.43, torch, transformers, safetensors,
gradio_client, opencv-python-headless, Pillow, hf_xet.
"""
import os
os.environ.setdefault("HF_XET_HIGH_PERFORMANCE", "1")
import copy
import types
import torch
import torch.nn as nn
import torch.nn.functional as F
from safetensors.torch import load_file
BASE = "MiniMaxAI/MiniMax-H3-Image"
CONTROLNET_REPO = "alibaba-pai/MiniMax-H3-Fun-Controlnet-Union-2.0"
CONTROLNET_FILE = "MiniMax-H3-Fun-Controlnet-Union-2.0.safetensors"
ENCODER_SPACE = "CozyByte/minimax-h3-image-encoder"
OUT = "/work/out"
os.makedirs(OUT, exist_ok=True)
CONTROL_BLOCKS_PLACES = list(range(0, 50, 5)) # 0,5,...,45 -> 10 blocks
SEED = 904231
PROMPT = "A cozy cabin in a snowy pine forest at dusk, warm light in the windows, photorealistic."
# ImageNet normalization used by the VideoX-Fun control pipeline before the VAE encode.
PIXEL_MEAN = (0.485, 0.456, 0.406)
PIXEL_STD = (0.229, 0.224, 0.225)
def log(msg):
import time
print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True)
# ---------------------------------------------------------------- attach ----
def attach_control_branch(model, ckpt_path, control_in_dim=49):
"""Add control_proj_in + 10 control blocks to MiniMaxH3ImageTransformer2DModel.
Control blocks are architecturally identical to main blocks (same key names)
plus a zero-init after_proj on every block and a zero-init before_proj on
block 0. Weights load verbatim from the VideoX-Fun checkpoint.
"""
hidden = model.config.hidden_size
model.control_proj_in = nn.Linear(control_in_dim * 4, hidden, bias=True)
proto = model.transformer_blocks[0]
blocks = nn.ModuleList()
for i in range(len(CONTROL_BLOCKS_PLACES)):
blk = copy.deepcopy(proto)
blk.after_proj = nn.Linear(hidden, hidden, bias=True)
nn.init.zeros_(blk.after_proj.weight)
nn.init.zeros_(blk.after_proj.bias)
if i == 0:
blk.before_proj = nn.Linear(hidden, hidden, bias=True)
nn.init.zeros_(blk.before_proj.weight)
nn.init.zeros_(blk.before_proj.bias)
blocks.append(blk)
model.control_blocks = blocks
sd = load_file(ckpt_path)
ctl = {k: v for k, v in sd.items() if k.startswith("control_")}
# assign=True: also correct when the model was built under init_empty_weights
# (meta params) — without it the load is a silent no-op on meta tensors.
missing, unexpected = model.load_state_dict(ctl, strict=False, assign=True)
# The ckpt is float32 and load_state_dict casts params in place; the base
# transformer runs in bf16, so cast the whole control branch back to match.
main_dtype = model.transformer_blocks[0].attn.to_q.weight.dtype
model.control_proj_in.to(dtype=main_dtype)
model.control_blocks.to(dtype=main_dtype)
missing = [k for k in missing if k.startswith("control_")]
unexpected = [k for k in unexpected if k.startswith("control_")]
log(f"control weights: {len(ctl)} tensors; missing={len(missing)} unexpected={len(unexpected)}")
assert not missing and not unexpected, (missing[:5], unexpected[:5])
return model
def wrap_forward_with_control(model):
"""Replace model.forward with a control-aware version.
Mirrors the installed diffusers MiniMaxH3ImageTransformer2DModel.forward
(ref_transformer_minimax_h3_image.py) statement for statement, inserting the
VideoX-Fun control-branch semantics
(videox_fun/models/minimax_h3_transformer3d_control.py):
- c = packed seq with image rows replaced by control_proj_in(control_rows)
(via index_copy(1, image_indices, ...), text rows identical)
- control block 0: c = before_proj(c) + packed (the main packed input);
each control block emits hint_k = after_proj(block_k(c)); the stream
handed to the next control block is the block output (hints only
accumulate).
- main blocks at CONTROL_BLOCKS_PLACES: h += hint_k * control_context_scale
control_rows=None runs the base forward verbatim (no control overhead).
The extra kwargs are declared in the signature so the modular denoiser block
forwards them from denoiser_input_fields.
"""
from diffusers.models.modeling_utils import get_parameter_dtype
from diffusers.models.transformers.transformer_minimax_h3_image import (
MINIMAX_H3_MODALITY_NUM,
)
from diffusers.models.modeling_outputs import Transformer2DModelOutput
orig_forward = model.forward
def forward(
self,
hidden_states,
encoder_hidden_states,
timestep,
timestep_indices,
token_tags,
position_ids,
image_indices,
text_indices,
pdd_step_index,
return_dict=True,
control_rows=None,
control_context_scale=1.0,
):
if control_rows is None:
return orig_forward(
hidden_states=hidden_states,
encoder_hidden_states=encoder_hidden_states,
timestep=timestep,
timestep_indices=timestep_indices,
token_tags=token_tags,
position_ids=position_ids,
image_indices=image_indices,
text_indices=text_indices,
pdd_step_index=pdd_step_index,
return_dict=return_dict,
)
if position_ids.ndim != 2 or position_ids.shape[-1] != 3:
raise ValueError(f"`position_ids` must be a `(seq_len, 3)` tensor, got {list(position_ids.shape)}.")
sequence_length = position_ids.shape[0]
if token_tags.shape != (sequence_length,) or timestep_indices.shape != (sequence_length,):
raise ValueError(
"`token_tags` and `timestep_indices` must both be `(seq_len,)` tensors matching `position_ids`, got "
f"{list(token_tags.shape)} and {list(timestep_indices.shape)} for seq_len={sequence_length}."
)
if control_rows.shape[1] != image_indices.shape[0]:
raise ValueError(
f"`control_rows` carries {control_rows.shape[1]} rows but the packed sequence has "
f"{image_indices.shape[0]} image rows. One control row per image row of `hidden_states` is required, "
"in the same order."
)
rotary_emb = self.rope(position_ids)
# 1. Modality projections and the packed sequence buffer, identical to the base forward.
image_embeds = self.proj_in(hidden_states.to(get_parameter_dtype(self.proj_in)))
text_embeds = self.context_embedder(encoder_hidden_states.to(get_parameter_dtype(self.context_embedder)))
text_embeds = self.token_refiner(text_embeds)
hidden_states = text_embeds.new_zeros((text_embeds.shape[0], sequence_length, text_embeds.shape[-1]))
hidden_states = hidden_states.index_copy(1, text_indices, text_embeds)
hidden_states = hidden_states.index_copy(1, image_indices, image_embeds.to(text_embeds.dtype))
# 2. Timestep embedding and AdaLN table rows, identical to the base forward; the control stream shares them.
temb = self.time_proj(timestep)
temb = self.time_embedder(temb.to(get_parameter_dtype(self.time_embedder)))
adaln_indices = timestep_indices * MINIMAX_H3_MODALITY_NUM + token_tags
# 3. Control branch over the packed sequence: the control stream carries the control rows at the image
# positions and the main branch's own features at the text rows, so it shares the main branch's timestep
# embeddings, AdaLN table rows and rotary coordinates. The first control block re-bases it on the main
# branch's packed sequence via `before_proj`; every control block emits one `after_proj` skip.
control_embeds = self.control_proj_in(control_rows.to(get_parameter_dtype(self.control_proj_in)))
c = hidden_states.index_copy(1, image_indices, control_embeds.to(hidden_states.dtype))
hints = []
for n, block in enumerate(self.control_blocks):
if n == 0:
c = block.before_proj(c) + hidden_states
c = block(c, temb, adaln_indices, rotary_emb)
hints.append(block.after_proj(c))
# 4. Main block stack with the control skips injected at the addressed layers.
for i, block in enumerate(self.transformer_blocks):
if torch.is_grad_enabled() and self.gradient_checkpointing:
hidden_states = self._gradient_checkpointing_func(
block, hidden_states, temb, adaln_indices, rotary_emb
)
else:
hidden_states = block(hidden_states, temb, adaln_indices, rotary_emb)
if i in CONTROL_BLOCKS_PLACES:
k = CONTROL_BLOCKS_PLACES.index(i)
hidden_states = hidden_states + hints[k] * control_context_scale
# 5. Output head of this step, identical to the base forward.
proj_out = self.pdd_proj_out[pdd_step_index]
hidden_states = self.norm_out(hidden_states, temb, timestep_indices).to(get_parameter_dtype(proj_out))
output = proj_out(hidden_states).index_select(1, image_indices)
if not return_dict:
return (output,)
return Transformer2DModelOutput(sample=output)
model.forward = types.MethodType(forward, model)
return model
# ---------------------------------------------------------- control rows ----
def build_control_rows(pipe, control_image_rgb, latent_height, latent_width, patch_size=(1, 2, 2)):
"""VAE-encode a control image into control rows, exactly as the VideoX-Fun
control pipeline does (pipeline_minimax_h3_control.py):
pixels [0,1] -> ImageNet normalize -> VAE encode, latent_dist.mode()
-> (z - latents_mean) / latents_std -> patchify (1,2,2)
-> zero-pad 96 -> 196 cols (trained no-inpaint layout).
The control image is resized to the generation canvas so the rows line up
1:1 with the image rows of the packed sequence (frame-major, row-major).
Returns a float32 tensor of shape (1, (lat_h/2)*(lat_w/2), 196) on cuda.
"""
import numpy as np
from PIL import Image
vae = pipe.vae
device = pipe._execution_device
ratio = getattr(pipe, "vae_spatial_compression_ratio", 16)
image = Image.fromarray(control_image_rgb).resize(
(latent_width * ratio, latent_height * ratio), Image.LANCZOS
)
pixels = torch.from_numpy(np.array(image)).to(device).permute(2, 0, 1)[None].float() / 255.0
mean = torch.tensor(PIXEL_MEAN, device=device).view(1, -1, 1, 1)
std = torch.tensor(PIXEL_STD, device=device).view(1, -1, 1, 1)
pixels = (pixels - mean) / std
with torch.no_grad():
posterior = vae.encode(pixels.to(vae.dtype), return_dict=False)[0]
z = posterior.mode().float()
latents_mean = torch.tensor(vae.config.latents_mean, device=device).view(1, -1, 1, 1)
latents_std = torch.tensor(vae.config.latents_std, device=device).view(1, -1, 1, 1)
z = (z - latents_mean) / latents_std
# The 2D image VAE emits (B, 24, H, W); patchify (2, 2) over (H, W), frame=1.
# Row order is row-major, same as the pipeline's packed image rows.
pt, ph, pw = patch_size
assert pt == 1, "2D VAE has a single latent frame"
b, ch, h, w = z.shape
rows = z.reshape(b, ch, h // ph, ph, w // pw, pw)
rows = rows.permute(0, 2, 4, 1, 3, 5).reshape(b, -1, ch * ph * pw)
control_in_dim = pipe.transformer.control_proj_in.in_features // (pt * ph * pw)
expected = control_in_dim * pt * ph * pw
if rows.shape[-1] < expected:
rows = F.pad(rows, (0, expected - rows.shape[-1]))
elif rows.shape[-1] > expected:
raise ValueError(f"control rows have {rows.shape[-1]} cols but control_proj_in expects {expected}")
return rows.contiguous()
# ------------------------------------------------------------------ psnr ----
def psnr(img_a, img_b):
import numpy as np
a = np.asarray(img_a).astype(np.float64)
b = np.asarray(img_b).astype(np.float64)
mse = np.mean((a - b) ** 2)
if mse == 0:
return float("inf")
return 10 * np.log10(255.0**2 / mse)
# ------------------------------------------------------------ validation ----
def main():
from huggingface_hub import hf_hub_download
log("downloading control branch")
ckpt = hf_hub_download(CONTROLNET_REPO, CONTROLNET_FILE)
log("building modular pipeline (no text encoder; embeds from encoder Space)")
from diffusers import ModularPipeline
blocks = ModularPipeline.from_pretrained(BASE).blocks
blocks.sub_blocks.pop("text_encoder")
pipe = blocks.init_pipeline(BASE)
pipe.load_components(dtype=torch.bfloat16)
model = pipe.transformer
log(f"transformer: {sum(p.numel() for p in model.parameters())/1e9:.1f}B params")
attach_control_branch(model, ckpt)
wrap_forward_with_control(model)
pipe.to("cuda")
log("pipeline on cuda")
# control image: canny edges of a real photo (from base repo examples)
import cv2
import numpy as np
from PIL import Image
ref = hf_hub_download(BASE, "examples/reference1.png")
img = np.asarray(Image.open(ref).convert("RGB"))
edges = cv2.Canny(cv2.cvtColor(img, cv2.COLOR_RGB2GRAY), 100, 200)
canny_rgb = np.repeat(edges[..., None], 3, axis=-1)
Image.fromarray(canny_rgb).save(f"{OUT}/control_canny.png")
log(f"saved {OUT}/control_canny.png")
# prompt embeds from the public encoder Space (same trick as the official demo)
from gradio_client import Client
from safetensors import safe_open
client = Client(ENCODER_SPACE, token=os.environ.get("HF_TOKEN"), httpx_kwargs={"timeout": 600})
try:
embeds_path = client.predict(PROMPT, [], api_name="/encode")
except Exception as e:
log(f"empty image list rejected ({e}); retrying with a white PNG")
from gradio_client import handle_file
white = "/tmp/white.png"
Image.new("RGB", (64, 64), (255, 255, 255)).save(white)
embeds_path = client.predict(PROMPT, [handle_file(white)], api_name="/encode")
if isinstance(embeds_path, (tuple, list)):
embeds_path = embeds_path[0]
if isinstance(embeds_path, dict):
embeds_path = embeds_path["path"]
with safe_open(embeds_path, framework="pt") as h:
prompt_embeds = h.get_tensor("prompt_embeds")
text_token_tags = h.get_tensor("text_token_tags")
log(f"prompt embeds: {tuple(prompt_embeds.shape)}")
def generate(control_rows, scale, tag):
result = pipe(
prompt_embeds=prompt_embeds.to("cuda", torch.bfloat16),
text_token_tags=text_token_tags,
width=1024,
height=1024,
min_generation_area=1024,
generator=torch.Generator("cpu").manual_seed(SEED),
output="images",
# control kwargs reach the wrapped transformer forward:
denoiser_input_fields={
"control_rows": control_rows,
"control_context_scale": scale,
},
)
result[0].save(f"{OUT}/{tag}.png")
peak = torch.cuda.max_memory_allocated() / 2**30
log(f"saved {OUT}/{tag}.png (peak GPU {peak:.1f} GiB)")
return result[0]
# 1. base: no control rows
base = generate(None, 1.0, "t2i_base")
# control rows from the canny edge map, aligned with the 1024x1024 canvas
ratio = getattr(pipe, "vae_spatial_compression_ratio", 16)
control_rows = build_control_rows(pipe, canny_rgb, 1024 // ratio, 1024 // ratio)
log(f"control rows: {tuple(control_rows.shape)} {control_rows.dtype}")
# 2. wiring sanity: control rows but scale 0 -> must match base
gated = generate(control_rows, 0.0, "t2i_control_scale0.0")
log(f"PSNR(scale0.0 vs base) = {psnr(base, gated):.2f} dB (expect > 40 dB)")
# 3. control at increasing scales
for scale in (0.5, 1.0):
out = generate(control_rows, scale, f"t2i_control_scale{scale}")
log(f"PSNR(scale{scale} vs base) = {psnr(base, out):.2f} dB (expect LOW)")
# persist outputs to the merge repo (job/sandbox storage is ephemeral)
from huggingface_hub import HfApi
HfApi().upload_folder(
folder_path=OUT,
path_in_repo="assets/validation",
repo_id="akhaliq/MiniMax-H3-Image-Fun-Controlnet-Union-2.0",
repo_type="model",
commit_message="Validation: control branch on H3-Image, canny t2i at scales 0/0.5/1.0",
)
log("outputs uploaded to assets/validation/")
log("DONE")
if __name__ == "__main__":
main()