"""Merge ComfyUI-format or Diffusers-format MiniMax-H3 LoRA weights into a BF16 transformer on CPU.""" from __future__ import annotations import os import re import time import torch from huggingface_hub import hf_hub_download from safetensors.torch import load_file _CHUNK_ROWS = 512 # Direct 2-D projections in the ComfyUI/reference MiniMax-H3 tree whose row layout matches Diffusers. _REFERENCE_MODULES = { "video_patch_proj": "proj_in", "audio_patch_proj": "audio_proj_in", "condition_proj": "context_embedder", "time_embedder.proj_in": "time_embedder.linear_1", "time_embedder.proj_out": "time_embedder.linear_2", "final_layer.adaln_proj.linear": "norm_out.linear", "final_layer.video_out": "proj_out", "final_layer.audio_out": "audio_proj_out", } _BLOCK_INDEX_RE = re.compile(r"^transformer_blocks\.(\d+)\.") def _strip_lora_prefix(name: str) -> str: for prefix in ("diffusion_model.", "transformer.", "base_model.model."): if name.startswith(prefix): return name[len(prefix):] return name def _convert_reference_target(name: str, b: torch.Tensor, inner_dim: int) -> list[tuple[str, torch.Tensor]]: """Map a ComfyUI/reference H3 LoRA base name and its lora_B tensor onto Diffusers submodule(s).""" clean = _strip_lora_prefix(name) if clean in _REFERENCE_MODULES: return [(_REFERENCE_MODULES[clean], b)] if clean.startswith("token_refiner.blocks."): target = clean.replace("token_refiner.blocks.", "token_refiner.refiner_blocks.", 1) elif clean.startswith("blocks."): target = clean.replace("blocks.", "transformer_blocks.", 1) else: target = clean if target.endswith(".attn.qkv_proj"): prefix = target.removesuffix("qkv_proj") if b.shape[0] != 3 * inner_dim: raise ValueError(f"Expected 3 * inner_dim ({3 * inner_dim}) rows for {name}, got {b.shape[0]}") return [ (f"{prefix}to_{kind}", part.contiguous()) for kind, part in zip(("q", "k", "v"), b.split(inner_dim, dim=0)) ] if target.endswith(".mlp.fc1"): # ComfyUI stores SwiGLU as [gate, up], whereas Diffusers SwiGLUFeedForward expects [up, gate]. gate, value = b.chunk(2, dim=0) return [(target.replace(".mlp.fc1", ".ff.net.0.proj"), torch.cat([value, gate], dim=0).contiguous())] if target.endswith(".mlp.fc2"): return [(target.replace(".mlp.fc2", ".ff.net.2"), b)] if target.endswith(".attn.out_proj"): return [(target.replace(".attn.out_proj", ".attn.to_out.0"), b)] return [(target, b)] def _parse_lora_pairs(lora_sd: dict[str, torch.Tensor]) -> dict[str, dict[str, torch.Tensor]]: pairs: dict[str, dict[str, torch.Tensor]] = {} for key, tensor in lora_sd.items(): if key.endswith(".lora_A.default.weight"): base, role = key[: -len(".lora_A.default.weight")], "A" elif key.endswith(".lora_B.default.weight"): base, role = key[: -len(".lora_B.default.weight")], "B" elif key.endswith(".lora_A.weight"): base, role = key[: -len(".lora_A.weight")], "A" elif key.endswith(".lora_B.weight"): base, role = key[: -len(".lora_B.weight")], "B" elif key.endswith(".lora_down.weight"): base, role = key[: -len(".lora_down.weight")], "A" elif key.endswith(".lora_up.weight"): base, role = key[: -len(".lora_up.weight")], "B" elif key.endswith(".alpha"): base, role = key[: -len(".alpha")], "alpha" elif key.endswith(".lora_alpha"): base, role = key[: -len(".lora_alpha")], "alpha" else: continue pairs.setdefault(base, {})[role] = tensor return pairs def _module_scale( target_name: str, scale: float, attn_scale: float, mlp_scale: float, early_blocks: int, early_scale: float, audio_scale: float, ) -> float: mult = scale if ".attn." in target_name: mult *= attn_scale elif ".ff." in target_name: mult *= mlp_scale elif target_name in ("audio_proj_in", "audio_proj_out"): mult *= audio_scale if early_blocks > 0 and early_scale != 1.0: match = _BLOCK_INDEX_RE.match(target_name) if match and int(match.group(1)) < early_blocks: mult *= early_scale return mult @torch.no_grad() def merge_h3_lora_from_state_dict( transformer: torch.nn.Module, lora_sd: dict[str, torch.Tensor], *, scale: float = 1.0, attn_scale: float = 1.0, mlp_scale: float = 1.0, early_blocks: int = 0, early_scale: float = 1.0, audio_scale: float = 1.0, ) -> int: """Merge a MiniMax-H3 LoRA state dict into a BF16/FP32 Diffusers transformer in place.""" if scale == 0.0: return 0 inner_dim = int(transformer.config.num_attention_heads) * int(transformer.config.attention_head_dim) pairs = _parse_lora_pairs(lora_sd) if not pairs: raise ValueError("No LoRA A/B weight pairs found in state dict.") merged = 0 for base, entry in pairs.items(): if "A" not in entry or "B" not in entry: raise ValueError(f"Incomplete LoRA pair for {base!r}: keys={tuple(entry.keys())}") a = entry["A"].to(dtype=torch.float32, device="cpu") b = entry["B"].to(dtype=torch.float32, device="cpu") if a.ndim != 2 or b.ndim != 2 or b.shape[1] != a.shape[0]: raise ValueError(f"Invalid LoRA shapes for {base!r}: A={tuple(a.shape)}, B={tuple(b.shape)}") rank = a.shape[0] alpha_tensor = entry.get("alpha") alpha = float(alpha_tensor.item()) if alpha_tensor is not None else float(rank) rank_scale = alpha / float(rank) for target_name, b_part in _convert_reference_target(base, b, inner_dim): module = transformer.get_submodule(target_name) if not isinstance(module, torch.nn.Linear): raise ValueError(f"Target module {target_name!r} is {type(module).__name__}, expected torch.nn.Linear") w = module.weight.detach() if (b_part.shape[0], a.shape[1]) != tuple(w.shape): raise ValueError( f"Shape mismatch for {target_name!r}: LoRA {(b_part.shape[0], a.shape[1])} vs weight {tuple(w.shape)}" ) eff_scale = rank_scale * _module_scale( target_name, scale, attn_scale, mlp_scale, early_blocks, early_scale, audio_scale ) if abs(eff_scale) <= 1e-8: continue a_dev = a.to(device=w.device) b_dev = b_part.to(device=w.device) for start in range(0, w.shape[0], _CHUNK_ROWS): end = min(start + _CHUNK_ROWS, w.shape[0]) chunk = w[start:end].to(torch.float32) chunk.addmm_(b_dev[start:end], a_dev, alpha=eff_scale) w[start:end].copy_(chunk.to(w.dtype)) merged += 1 return merged def merge_h3_lora( transformer: torch.nn.Module, *, repo_id: str | None = None, filename: str | None = None, revision: str | None = None, scale: float | None = None, attn_scale: float | None = None, mlp_scale: float | None = None, early_blocks: int | None = None, early_scale: float | None = None, audio_scale: float | None = None, ) -> tuple[int, str]: """Download and merge a Hugging Face MiniMax-H3 LoRA into ``transformer`` in place.""" repo_id = (repo_id if repo_id is not None else os.environ.get("LORA_REPO", "")).strip() filename = (filename if filename is not None else os.environ.get("LORA_FILENAME", "")).strip() revision = (revision if revision is not None else os.environ.get("LORA_REVISION", "main")).strip() or "main" scale = float(os.environ.get("LORA_SCALE", "1.0")) if scale is None else float(scale) attn_scale = float(os.environ.get("LORA_ATTN_SCALE", "1.0")) if attn_scale is None else float(attn_scale) mlp_scale = float(os.environ.get("LORA_MLP_SCALE", "1.0")) if mlp_scale is None else float(mlp_scale) early_blocks = int(os.environ.get("LORA_EARLY_BLOCKS", "0")) if early_blocks is None else int(early_blocks) early_scale = float(os.environ.get("LORA_EARLY_SCALE", "1.0")) if early_scale is None else float(early_scale) audio_scale = float(os.environ.get("LORA_AUDIO_SCALE", "1.0")) if audio_scale is None else float(audio_scale) if not repo_id or not filename or scale == 0.0: return 0, "" t0 = time.perf_counter() lora_path = hf_hub_download(repo_id=repo_id, filename=filename, revision=revision) lora_sd = load_file(lora_path, device="cpu") try: merged = merge_h3_lora_from_state_dict( transformer, lora_sd, scale=scale, attn_scale=attn_scale, mlp_scale=mlp_scale, early_blocks=early_blocks, early_scale=early_scale, audio_scale=audio_scale, ) finally: lora_sd.clear() elapsed = time.perf_counter() - t0 print(f"Merged custom adapter (scale={scale}, modules={merged}) in {elapsed:.1f}s", flush=True) return merged, f"{repo_id}/{filename}"