Text-to-Image
Diffusers
Safetensors
MiniMax H3
VideoX Fun
controlnet
controlnet-union
image-to-image
ml-intern
Instructions to use akhaliq/MiniMax-H3-Image-Fun-Controlnet-Union-2.0 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Diffusers
How to use akhaliq/MiniMax-H3-Image-Fun-Controlnet-Union-2.0 with Diffusers:
pip install -U diffusers transformers accelerate
from diffusers import ControlNetModel, StableDiffusionControlNetPipeline controlnet = ControlNetModel.from_pretrained("akhaliq/MiniMax-H3-Image-Fun-Controlnet-Union-2.0") pipe = StableDiffusionControlNetPipeline.from_pretrained( "MiniMaxAI/MiniMax-H3-Image", controlnet=controlnet ) - VideoX Fun
How to use akhaliq/MiniMax-H3-Image-Fun-Controlnet-Union-2.0 with VideoX Fun:
# No code snippets available yet for this library. # To use this model, check the repository files and the library's documentation. # Want to help? PRs adding snippets are welcome at: # https://github.com/huggingface/huggingface.js
- Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- Draw Things
- DiffusionBee
merge/: ph3-control recipe port (v1 branch, 2-frame, video temb)
Browse files- merge/expE_ph3.py +416 -0
merge/expE_ph3.py
ADDED
|
@@ -0,0 +1,416 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Experiment E: port the ph3-control recipe (RubenTorney/comfyui-ph3-control, Nov 2026)
|
| 2 |
+
to base MiniMax-H3-Image with the v1 H3-Fun-ControlNet branch, in diffusers.
|
| 3 |
+
|
| 4 |
+
Recipe (from ph3_control/patch.py, measured PCK 0.435->0.815 on P-H3-Image):
|
| 5 |
+
1. v1 branch (5 control blocks at layers 0,10,20,30,40), NOT v2.0
|
| 6 |
+
2. base model runs 2 latent frames (frozen mini-video); control image encoded as a
|
| 7 |
+
5-frame video -> 2 latent frames; residual added to FRAME-0 TARGET ROWS only
|
| 8 |
+
3. control active on the FIRST 50% of steps, strength 1.2
|
| 9 |
+
4. control branch gets the VIDEO model's time embedding (their adaLN 16->8 table;
|
| 10 |
+
here we feed the true video temb — strictly the training condition)
|
| 11 |
+
|
| 12 |
+
Runs (1024x1024, 8 steps, shift-12 grid, seed 904231, cabin prompt, canny control):
|
| 13 |
+
base2f.png — 2-frame base, no control (sanity: frame 0 coherent)
|
| 14 |
+
ctrl_image_temb.png — control with image temb (adaLN ablation)
|
| 15 |
+
ctrl_video_temb.png — full recipe (video temb for the control stream)
|
| 16 |
+
Uploads to assets/validation7/.
|
| 17 |
+
"""
|
| 18 |
+
import os
|
| 19 |
+
import subprocess
|
| 20 |
+
import sys
|
| 21 |
+
import time
|
| 22 |
+
|
| 23 |
+
os.environ.setdefault("HF_XET_HIGH_PERFORMANCE", "1")
|
| 24 |
+
WORK = "/work"
|
| 25 |
+
OUT = f"{WORK}/out"
|
| 26 |
+
os.makedirs(OUT, exist_ok=True)
|
| 27 |
+
|
| 28 |
+
BASE = "MiniMaxAI/MiniMax-H3-Image"
|
| 29 |
+
VIDEO_REPO = "MiniMaxAI/MiniMax-H3"
|
| 30 |
+
V1_REPO = "alibaba-pai/MiniMax-H3-Fun-Controlnet-Union"
|
| 31 |
+
V1_FILE = "MiniMax-H3-Fun-Controlnet-Union.safetensors"
|
| 32 |
+
MERGE_REPO = "akhaliq/MiniMax-H3-Image-Fun-Controlnet-Union-2.0"
|
| 33 |
+
ENCODER_SPACE = "CozyByte/minimax-h3-image-encoder"
|
| 34 |
+
SEED = 904231
|
| 35 |
+
NUM_STEPS = 8
|
| 36 |
+
SHIFT = 12.0
|
| 37 |
+
STRENGTH = 1.2
|
| 38 |
+
CONTROL_FRAC = 0.5
|
| 39 |
+
PLACES = [0, 10, 20, 30, 40]
|
| 40 |
+
PROMPT = "A cozy cabin in a snowy pine forest at dusk, warm light in the windows, photorealistic."
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def log(m):
|
| 44 |
+
print(f"[{time.strftime('%H:%M:%S')}] {m}", flush=True)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def sh(cmd):
|
| 48 |
+
subprocess.run(cmd, check=True)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
sh([sys.executable, "-m", "pip", "install", "--no-cache-dir", "-q", "torch", "torchvision",
|
| 52 |
+
"--index-url", "https://download.pytorch.org/whl/cu126"])
|
| 53 |
+
sh([sys.executable, "-m", "pip", "install", "--no-cache-dir", "-q",
|
| 54 |
+
"numpy", "diffusers>=0.43", "transformers", "accelerate", "safetensors",
|
| 55 |
+
"gradio_client", "opencv-python-headless", "hf_xet", "Pillow"])
|
| 56 |
+
|
| 57 |
+
import json
|
| 58 |
+
import re
|
| 59 |
+
from glob import glob
|
| 60 |
+
|
| 61 |
+
import cv2
|
| 62 |
+
import numpy as np
|
| 63 |
+
import torch
|
| 64 |
+
import torch.nn as nn
|
| 65 |
+
import torch.nn.functional as F
|
| 66 |
+
from PIL import Image
|
| 67 |
+
from huggingface_hub import hf_hub_download, snapshot_download
|
| 68 |
+
from safetensors.torch import load_file
|
| 69 |
+
|
| 70 |
+
# ---------------- downloads ----------------
|
| 71 |
+
log("downloading models")
|
| 72 |
+
snap = snapshot_download(BASE, allow_patterns=[
|
| 73 |
+
"transformer/*", "vae_diffusers/*", "scheduler/*", "transformer_diffusers/config.json",
|
| 74 |
+
])
|
| 75 |
+
v1_ckpt = hf_hub_download(V1_REPO, V1_FILE)
|
| 76 |
+
video_vae_path = snapshot_download(VIDEO_REPO, allow_patterns=["vae/*"])
|
| 77 |
+
# video time_embedder tensors only (find shards via index)
|
| 78 |
+
vidx = json.load(open(hf_hub_download(VIDEO_REPO, "FL2VA/transformer/model.safetensors.index.json")))["weight_map"]
|
| 79 |
+
te_keys = [k for k in vidx if k.startswith("time_embedder.") or k.startswith("time_proj.")]
|
| 80 |
+
te_shards = sorted({vidx[k] for k in te_keys})
|
| 81 |
+
te_sd = {}
|
| 82 |
+
for shard in te_shards:
|
| 83 |
+
p = hf_hub_download(VIDEO_REPO, f"FL2VA/transformer/{shard}")
|
| 84 |
+
with __import__("safetensors").safe_open(p, framework="pt") as f:
|
| 85 |
+
for k in te_keys:
|
| 86 |
+
if vidx[k] == shard:
|
| 87 |
+
te_sd[k] = f.get_tensor(k)
|
| 88 |
+
os.remove(p)
|
| 89 |
+
log(f"video time_embedder tensors: {len(te_sd)}")
|
| 90 |
+
|
| 91 |
+
# ---------------- remap native image DiT (verified bit-exact) ----------------
|
| 92 |
+
from accelerate import init_empty_weights
|
| 93 |
+
from diffusers import AutoencoderKLMiniMaxH3, AutoencoderKLMiniMaxH3Image, MiniMaxH3Scheduler
|
| 94 |
+
from diffusers.models.transformers.transformer_minimax_h3_image import (
|
| 95 |
+
MiniMaxH3ImageTransformer2DModel,
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
cfg = json.load(open(f"{snap}/transformer_diffusers/config.json"))
|
| 99 |
+
cfg["num_pdd_heads"] = 1
|
| 100 |
+
with init_empty_weights():
|
| 101 |
+
model = MiniMaxH3ImageTransformer2DModel.from_config(cfg)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def _sub_map(sub):
|
| 105 |
+
if sub.startswith("attn.out_proj."):
|
| 106 |
+
return "attn.to_out.0." + sub[len("attn.out_proj."):]
|
| 107 |
+
if sub.startswith("attn.q_norm."):
|
| 108 |
+
return "attn.norm_q." + sub[len("attn.q_norm."):]
|
| 109 |
+
if sub.startswith("attn.k_norm."):
|
| 110 |
+
return "attn.norm_k." + sub[len("attn.k_norm."):]
|
| 111 |
+
if sub.startswith("mlp.fc1."):
|
| 112 |
+
return "ff.net.0.proj." + sub[len("mlp.fc1."):]
|
| 113 |
+
if sub.startswith("mlp.fc2."):
|
| 114 |
+
return "ff.net.2." + sub[len("mlp.fc2."):]
|
| 115 |
+
if sub.startswith("adaln_proj."):
|
| 116 |
+
s = sub[len("adaln_proj."):]
|
| 117 |
+
return sub if s.startswith("linear.") else "adaln_proj.linear." + s
|
| 118 |
+
return sub
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def remap_key(k):
|
| 122 |
+
if k.startswith("blocks."):
|
| 123 |
+
n, sub = k[len("blocks."):].split(".", 1)
|
| 124 |
+
return f"transformer_blocks.{n}." + _sub_map(sub)
|
| 125 |
+
if k.startswith("token_refiner.blocks."):
|
| 126 |
+
n, sub = k[len("token_refiner.blocks."):].split(".", 1)
|
| 127 |
+
return f"token_refiner.refiner_blocks.{n}." + _sub_map(sub)
|
| 128 |
+
for old, new in [("video_patch_proj.", "proj_in."), ("condition_proj.", "context_embedder."),
|
| 129 |
+
("final_layer.video_out.", "pdd_proj_out.0."), ("final_layer.adaln_proj.", "norm_out."),
|
| 130 |
+
("final_layer.norm.", "norm_out.norm."), ("time_embedder.proj_in.", "time_embedder.linear_1."),
|
| 131 |
+
("time_embedder.proj_out.", "time_embedder.linear_2.")]:
|
| 132 |
+
if k.startswith(old):
|
| 133 |
+
return new + k[len(old):]
|
| 134 |
+
return k
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def qkv_prefix(k):
|
| 138 |
+
if k.startswith("blocks."):
|
| 139 |
+
n = re.match(r"blocks\.(\d+)\.", k).group(1)
|
| 140 |
+
return f"transformer_blocks.{n}.attn."
|
| 141 |
+
n = re.match(r"token_refiner\.blocks\.(\d+)\.", k).group(1)
|
| 142 |
+
return f"token_refiner.refiner_blocks.{n}.attn."
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
remapped = {}
|
| 146 |
+
for shard in sorted(glob(f"{snap}/transformer/*.safetensors")):
|
| 147 |
+
for k, v in load_file(shard).items():
|
| 148 |
+
if k.endswith("attn.qkv_proj.weight"):
|
| 149 |
+
grouped = v.reshape(56, 384, *v.shape[1:])
|
| 150 |
+
q, kk, vv = grouped.split(128, dim=1)
|
| 151 |
+
pre = qkv_prefix(k)
|
| 152 |
+
remapped[pre + "to_q.weight"] = q.reshape(7168, *v.shape[1:]).contiguous()
|
| 153 |
+
remapped[pre + "to_k.weight"] = kk.reshape(7168, *v.shape[1:]).contiguous()
|
| 154 |
+
remapped[pre + "to_v.weight"] = vv.reshape(7168, *v.shape[1:]).contiguous()
|
| 155 |
+
continue
|
| 156 |
+
if k.endswith("mlp.fc1.weight"):
|
| 157 |
+
half = v.shape[0] // 2
|
| 158 |
+
v = torch.cat([v[half:], v[:half]], dim=0)
|
| 159 |
+
remapped[remap_key(k)] = v
|
| 160 |
+
if "time_embedder.linear_1.bias" not in remapped:
|
| 161 |
+
remapped["time_embedder.linear_1.bias"] = torch.zeros(5376)
|
| 162 |
+
missing = [k for k in model.state_dict() if k not in remapped]
|
| 163 |
+
assert not missing, f"missing {len(missing)}: {missing[:8]}"
|
| 164 |
+
model.load_state_dict(remapped, strict=False, assign=True)
|
| 165 |
+
model = model.to(torch.bfloat16)
|
| 166 |
+
for m_ in ("proj_in", "time_embedder", "pdd_proj_out", "rope"):
|
| 167 |
+
getattr(model, m_).to(torch.float32)
|
| 168 |
+
del remapped
|
| 169 |
+
log("native image DiT materialized (remap bit-exact)")
|
| 170 |
+
|
| 171 |
+
# ---------------- v1 control branch ----------------
|
| 172 |
+
import copy
|
| 173 |
+
import types
|
| 174 |
+
|
| 175 |
+
HIDDEN = model.config.hidden_size
|
| 176 |
+
model.control_proj_in = nn.Linear(49 * 4, HIDDEN, bias=True)
|
| 177 |
+
proto = model.transformer_blocks[0]
|
| 178 |
+
blocks = nn.ModuleList()
|
| 179 |
+
for i in range(len(PLACES)):
|
| 180 |
+
blk = copy.deepcopy(proto)
|
| 181 |
+
blk.after_proj = nn.Linear(HIDDEN, HIDDEN, bias=True)
|
| 182 |
+
nn.init.zeros_(blk.after_proj.weight)
|
| 183 |
+
nn.init.zeros_(blk.after_proj.bias)
|
| 184 |
+
if i == 0:
|
| 185 |
+
blk.before_proj = nn.Linear(HIDDEN, HIDDEN, bias=True)
|
| 186 |
+
nn.init.zeros_(blk.before_proj.weight)
|
| 187 |
+
nn.init.zeros_(blk.before_proj.bias)
|
| 188 |
+
blocks.append(blk)
|
| 189 |
+
model.control_blocks = blocks
|
| 190 |
+
sd = load_file(v1_ckpt)
|
| 191 |
+
ctl = {k: v for k, v in sd.items() if k.startswith("control_")}
|
| 192 |
+
log(f"v1 control tensors: {len(ctl)}; sample keys: {sorted(ctl)[:3]}")
|
| 193 |
+
missing, unexpected = model.load_state_dict(ctl, strict=False, assign=True)
|
| 194 |
+
missing = [k for k in missing if k.startswith("control_")]
|
| 195 |
+
unexpected = [k for k in unexpected if k.startswith("control_")]
|
| 196 |
+
log(f"v1 load: missing={len(missing)} unexpected={len(unexpected)}")
|
| 197 |
+
if missing or unexpected:
|
| 198 |
+
log(f" MISSING {missing[:6]}\n UNEXPECTED {unexpected[:6]}")
|
| 199 |
+
main_dtype = model.transformer_blocks[0].attn.to_q.weight.dtype
|
| 200 |
+
model.control_proj_in.to(dtype=main_dtype)
|
| 201 |
+
model.control_blocks.to(dtype=main_dtype)
|
| 202 |
+
del sd, ctl
|
| 203 |
+
|
| 204 |
+
# ---------------- video temb provider ----------------
|
| 205 |
+
vid_te = copy.deepcopy(model.time_embedder)
|
| 206 |
+
vid_map = {"time_embedder.proj_in.weight": "linear_1.weight",
|
| 207 |
+
"time_embedder.proj_in.bias": "linear_1.bias",
|
| 208 |
+
"time_embedder.proj_out.weight": "linear_2.weight",
|
| 209 |
+
"time_embedder.proj_out.bias": "linear_2.bias"}
|
| 210 |
+
vid_te_sd = {vid_map[k]: v for k, v in te_sd.items() if k in vid_map}
|
| 211 |
+
missing_te, unexp_te = vid_te.load_state_dict(vid_te_sd, strict=False)
|
| 212 |
+
assert not unexp_te, unexp_te
|
| 213 |
+
log(f"video time_embedder loaded (missing={list(missing_te)})")
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def video_temb(timestep):
|
| 217 |
+
from diffusers.models.modeling_utils import get_parameter_dtype
|
| 218 |
+
t = model.time_proj(timestep)
|
| 219 |
+
return vid_te(t.to(get_parameter_dtype(vid_te)))
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
# ---------------- forward wrap with ph3 semantics ----------------
|
| 223 |
+
from diffusers.models.modeling_utils import get_parameter_dtype
|
| 224 |
+
from diffusers.models.modeling_outputs import Transformer2DModelOutput
|
| 225 |
+
from diffusers.models.transformers.transformer_minimax_h3_image import MINIMAX_H3_MODALITY_NUM
|
| 226 |
+
|
| 227 |
+
orig_forward = model.forward
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def ph3_forward(self, hidden_states, encoder_hidden_states, timestep, timestep_indices,
|
| 231 |
+
token_tags, position_ids, image_indices, text_indices, pdd_step_index,
|
| 232 |
+
return_dict=True, control_rows=None, control_context_scale=1.0,
|
| 233 |
+
control_temb=None, frame0_image_rows=None):
|
| 234 |
+
if control_rows is None:
|
| 235 |
+
return orig_forward(hidden_states=hidden_states, encoder_hidden_states=encoder_hidden_states,
|
| 236 |
+
timestep=timestep, timestep_indices=timestep_indices, token_tags=token_tags,
|
| 237 |
+
position_ids=position_ids, image_indices=image_indices,
|
| 238 |
+
text_indices=text_indices, pdd_step_index=pdd_step_index, return_dict=return_dict)
|
| 239 |
+
|
| 240 |
+
rotary_emb = self.rope(position_ids)
|
| 241 |
+
image_embeds = self.proj_in(hidden_states.to(get_parameter_dtype(self.proj_in)))
|
| 242 |
+
text_embeds = self.context_embedder(encoder_hidden_states.to(get_parameter_dtype(self.context_embedder)))
|
| 243 |
+
text_embeds = self.token_refiner(text_embeds)
|
| 244 |
+
hs = text_embeds.new_zeros((text_embeds.shape[0], position_ids.shape[0], text_embeds.shape[-1]))
|
| 245 |
+
hs = hs.index_copy(1, text_indices, text_embeds)
|
| 246 |
+
hs = hs.index_copy(1, image_indices, image_embeds.to(text_embeds.dtype))
|
| 247 |
+
|
| 248 |
+
temb = self.time_proj(timestep)
|
| 249 |
+
temb = self.time_embedder(temb.to(get_parameter_dtype(self.time_embedder)))
|
| 250 |
+
adaln_indices = timestep_indices * MINIMAX_H3_MODALITY_NUM + token_tags
|
| 251 |
+
|
| 252 |
+
ctl_temb = control_temb if control_temb is not None else temb
|
| 253 |
+
control_embeds = self.control_proj_in(control_rows.to(get_parameter_dtype(self.control_proj_in)))
|
| 254 |
+
c = hs.index_copy(1, image_indices, control_embeds.to(hs.dtype))
|
| 255 |
+
hints = []
|
| 256 |
+
for n, block in enumerate(self.control_blocks):
|
| 257 |
+
if n == 0:
|
| 258 |
+
c = block.before_proj(c) + hs
|
| 259 |
+
c = block(c, ctl_temb, adaln_indices, rotary_emb)
|
| 260 |
+
hints.append(block.after_proj(c))
|
| 261 |
+
|
| 262 |
+
# ph3: residual on frame-0 target rows only
|
| 263 |
+
keep_rows = frame0_image_rows.to(hints[0].device)
|
| 264 |
+
place_idx = {p: k for k, p in enumerate(PLACES)}
|
| 265 |
+
for i, block in enumerate(self.transformer_blocks):
|
| 266 |
+
hs = block(hs, temb, adaln_indices, rotary_emb)
|
| 267 |
+
if i in place_idx:
|
| 268 |
+
hint = hints[place_idx[i]].clone()
|
| 269 |
+
mask = torch.ones(hint.shape[1], dtype=torch.bool, device=hint.device)
|
| 270 |
+
mask[keep_rows] = False
|
| 271 |
+
hint[:, mask] = 0
|
| 272 |
+
hs = hs + hint * control_context_scale
|
| 273 |
+
|
| 274 |
+
proj_out = self.pdd_proj_out[pdd_step_index]
|
| 275 |
+
hs = self.norm_out(hs, temb, timestep_indices).to(get_parameter_dtype(proj_out))
|
| 276 |
+
output = proj_out(hs).index_select(1, image_indices)
|
| 277 |
+
if not return_dict:
|
| 278 |
+
return (output,)
|
| 279 |
+
return Transformer2DModelOutput(sample=output)
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
model.forward = types.MethodType(ph3_forward, model)
|
| 283 |
+
model = model.cuda()
|
| 284 |
+
|
| 285 |
+
vae_img = AutoencoderKLMiniMaxH3Image.from_pretrained(BASE, subfolder="vae_diffusers", torch_dtype=torch.bfloat16).cuda()
|
| 286 |
+
vae_vid = AutoencoderKLMiniMaxH3.from_pretrained(VIDEO_REPO, subfolder="vae", torch_dtype=torch.bfloat16).cuda()
|
| 287 |
+
scheduler = MiniMaxH3Scheduler.from_pretrained(BASE, subfolder="scheduler")
|
| 288 |
+
log("model + v1 control + 2 VAEs on cuda")
|
| 289 |
+
|
| 290 |
+
# ---------------- prompt embeds ----------------
|
| 291 |
+
from gradio_client import Client
|
| 292 |
+
from safetensors import safe_open
|
| 293 |
+
|
| 294 |
+
client = Client(ENCODER_SPACE, token=os.environ.get("HF_TOKEN"), httpx_kwargs={"timeout": 600})
|
| 295 |
+
embeds_path = client.predict(PROMPT, [], api_name="/encode")
|
| 296 |
+
if isinstance(embeds_path, (tuple, list)):
|
| 297 |
+
embeds_path = embeds_path[0]
|
| 298 |
+
if isinstance(embeds_path, dict):
|
| 299 |
+
embeds_path = embeds_path["path"]
|
| 300 |
+
with safe_open(embeds_path, framework="pt") as h:
|
| 301 |
+
prompt_embeds = h.get_tensor("prompt_embeds")
|
| 302 |
+
text_token_tags = h.get_tensor("text_token_tags")
|
| 303 |
+
|
| 304 |
+
# ---------------- 2-frame layout ----------------
|
| 305 |
+
from diffusers.modular_pipelines.minimax_h3_image.before_denoise import (
|
| 306 |
+
_frame_position_grid, patchify_video_latents,
|
| 307 |
+
)
|
| 308 |
+
from diffusers.utils.torch_utils import randn_tensor
|
| 309 |
+
|
| 310 |
+
device = "cuda"
|
| 311 |
+
LAT = 64
|
| 312 |
+
n_text = prompt_embeds.shape[1]
|
| 313 |
+
frame_grid, _ = _frame_position_grid(LAT, LAT, 2, 2) # (1024, 2) fp64
|
| 314 |
+
n_img = LAT * LAT // 4
|
| 315 |
+
seq_len = n_text + 2 * n_img
|
| 316 |
+
|
| 317 |
+
position_ids = torch.zeros(seq_len, 3, dtype=torch.float64)
|
| 318 |
+
position_ids[:n_text, 0] = torch.arange(n_text, dtype=torch.float64)
|
| 319 |
+
position_ids[n_text:n_text + n_img, 0] = float(n_text)
|
| 320 |
+
position_ids[n_text:n_text + n_img, 1:] = frame_grid
|
| 321 |
+
position_ids[n_text + n_img:, 0] = float(n_text + 1)
|
| 322 |
+
position_ids[n_text + n_img:, 1:] = frame_grid
|
| 323 |
+
token_tags = torch.cat([text_token_tags.long(), torch.zeros(2 * n_img, dtype=torch.long)])
|
| 324 |
+
image_indices = torch.arange(n_text, seq_len)
|
| 325 |
+
text_indices = torch.arange(n_text)
|
| 326 |
+
frame0_rows = image_indices[:n_img].to(device)
|
| 327 |
+
position_ids = position_ids.to(device, torch.float32)
|
| 328 |
+
token_tags, image_indices, text_indices = token_tags.to(device), image_indices.to(device), text_indices.to(device)
|
| 329 |
+
log(f"2-frame packed: seq_len={seq_len} (text {n_text} + 2x{n_img})")
|
| 330 |
+
|
| 331 |
+
# ---------------- control video encode (5 frames -> 2 latent frames) ----------------
|
| 332 |
+
ref = hf_hub_download(BASE, "examples/reference1.png")
|
| 333 |
+
img = cv2.cvtColor(cv2.imread(ref), cv2.COLOR_BGR2RGB)
|
| 334 |
+
img = cv2.resize(img, (1024, 1024))
|
| 335 |
+
edges = cv2.Canny(cv2.cvtColor(img, cv2.COLOR_RGB2GRAY), 100, 200)
|
| 336 |
+
canny_rgb = np.repeat(edges[..., None], 3, axis=-1)
|
| 337 |
+
Image.fromarray(canny_rgb).save(f"{OUT}/control_canny.png")
|
| 338 |
+
|
| 339 |
+
frames = torch.from_numpy(canny_rgb).to(device).permute(2, 0, 1)[None, :, None].float() / 255.0
|
| 340 |
+
frames = frames.repeat(1, 1, 5, 1, 1) # (1,3,5,1024,1024)
|
| 341 |
+
mean = torch.tensor((0.485, 0.456, 0.406), device=device).view(1, -1, 1, 1, 1)
|
| 342 |
+
std = torch.tensor((0.229, 0.224, 0.225), device=device).view(1, -1, 1, 1, 1)
|
| 343 |
+
frames = (frames - mean) / std
|
| 344 |
+
with torch.no_grad():
|
| 345 |
+
posterior = vae_vid.encode(frames.to(vae_vid.dtype), return_dict=False)[0]
|
| 346 |
+
zc = posterior.mode().float()
|
| 347 |
+
lm = torch.tensor(vae_vid.config.latents_mean, device=device).view(1, -1, 1, 1, 1)
|
| 348 |
+
ls = torch.tensor(vae_vid.config.latents_std, device=device).view(1, -1, 1, 1, 1)
|
| 349 |
+
zc = (zc - lm) / ls
|
| 350 |
+
log(f"control latent: {tuple(zc.shape)}")
|
| 351 |
+
control_rows = patchify_video_latents(zc, (1, 2, 2))[None] # (1, 2048, 96)
|
| 352 |
+
control_rows = F.pad(control_rows, (0, 196 - control_rows.shape[-1]))
|
| 353 |
+
log(f"control rows: {tuple(control_rows.shape)}")
|
| 354 |
+
|
| 355 |
+
# ---------------- sampler ----------------
|
| 356 |
+
u = torch.linspace(1.0, 0.0, NUM_STEPS + 1)
|
| 357 |
+
sigmas = SHIFT * u / (1 + (SHIFT - 1) * u)
|
| 358 |
+
sigmas[-1] = 0.0
|
| 359 |
+
log(f"grid: {NUM_STEPS} steps shift={SHIFT}, sigmas {[round(float(x), 3) for x in sigmas[:4]]}...")
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
def decode_frame0(rows):
|
| 363 |
+
pt, ph, pw = 1, 2, 2
|
| 364 |
+
x = rows.reshape(1, 2, LAT // ph, LAT // pw, 24, pt, ph, pw)
|
| 365 |
+
x = x.permute(0, 4, 5, 1, 2, 6, 3, 7).reshape(1, 24, 2, LAT, LAT)
|
| 366 |
+
z = x[:, :, 0].float()
|
| 367 |
+
mean = torch.tensor(vae_img.config.latents_mean, device=device).view(1, -1, 1, 1)
|
| 368 |
+
std = torch.tensor(vae_img.config.latents_std, device=device).view(1, -1, 1, 1)
|
| 369 |
+
z = z * std + mean
|
| 370 |
+
with torch.no_grad():
|
| 371 |
+
img = vae_img.decode(z.to(torch.bfloat16), return_dict=False)[0]
|
| 372 |
+
img = (img.float() / 2 + 0.5).clamp(0, 1)[0].permute(1, 2, 0).cpu().numpy()
|
| 373 |
+
return Image.fromarray((img * 255).round().astype(np.uint8))
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
@torch.no_grad()
|
| 377 |
+
def generate(rows_ctrl, temb_fn, tag):
|
| 378 |
+
scheduler.set_timesteps(sigmas=sigmas, device=device)
|
| 379 |
+
ts = scheduler.timesteps
|
| 380 |
+
latents = patchify_video_latents(
|
| 381 |
+
randn_tensor((1, 24, 2, LAT, LAT), generator=torch.Generator("cpu").manual_seed(SEED),
|
| 382 |
+
device=device, dtype=torch.float32), (1, 2, 2))
|
| 383 |
+
n_steps = len(ts)
|
| 384 |
+
for i, t in enumerate(ts):
|
| 385 |
+
active = (i / n_steps) < CONTROL_FRAC
|
| 386 |
+
scale = STRENGTH if (rows_ctrl is not None and active) else 0.0
|
| 387 |
+
unique = torch.full((1,), float(t), dtype=torch.float32, device=device)
|
| 388 |
+
tidx = torch.zeros(seq_len, dtype=torch.long, device=device)
|
| 389 |
+
vel = model(
|
| 390 |
+
hidden_states=latents[None],
|
| 391 |
+
encoder_hidden_states=prompt_embeds.to(device, torch.bfloat16),
|
| 392 |
+
timestep=unique, timestep_indices=tidx, token_tags=token_tags,
|
| 393 |
+
position_ids=position_ids, image_indices=image_indices, text_indices=text_indices,
|
| 394 |
+
pdd_step_index=0, return_dict=False,
|
| 395 |
+
control_rows=rows_ctrl, control_context_scale=scale,
|
| 396 |
+
control_temb=temb_fn(unique) if (rows_ctrl is not None and temb_fn is not None) else None,
|
| 397 |
+
frame0_image_rows=frame0_rows,
|
| 398 |
+
)[0]
|
| 399 |
+
latents = scheduler.step(vel[0].float(), t, latents, return_dict=False)[0]
|
| 400 |
+
img = decode_frame0(latents)
|
| 401 |
+
img.save(f"{OUT}/{tag}.png")
|
| 402 |
+
log(f"saved {OUT}/{tag}.png (peak GPU {torch.cuda.max_memory_allocated()/2**30:.1f} GiB)")
|
| 403 |
+
return img
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
base = generate(None, None, "base2f")
|
| 407 |
+
gen_img_temb = generate(control_rows, None, "ctrl_image_temb")
|
| 408 |
+
gen_vid_temb = generate(control_rows, video_temb, "ctrl_video_temb")
|
| 409 |
+
|
| 410 |
+
from huggingface_hub import HfApi
|
| 411 |
+
|
| 412 |
+
HfApi().upload_folder(
|
| 413 |
+
folder_path=OUT, path_in_repo="assets/validation7", repo_id=MERGE_REPO, repo_type="model",
|
| 414 |
+
commit_message="ph3-control recipe port: v1 branch, 2-frame, 8-step shift-12, 50% gating, video temb",
|
| 415 |
+
)
|
| 416 |
+
log("ALL DONE")
|