Spaces:
Running on Zero
Running on Zero
feat(lora): add ComfyUI MiniMax-H3 LoRA conversion
Browse filesImplement automatic remapping of ComfyUI-format MiniMax-H3 Turbo LoRAs to diffusers module names.
- Added `_is_comfyui_lora` to detect ComfyUI naming conventions.
- Added `_convert_comfyui_lora` to handle:
- Block prefix remapping (`blocks` -> `transformer_blocks`).
- Token refiner path updates.
- Splitting fused QKV projections into separate `to_q`, `to_k`, and `to_v` weights.
- Remapping MLP and output projection keys.
- Integrated conversion into `apply_loras` to support Turbo LoRAs without manual conversion.
348 unmodified lines3493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224233564244254264274285 unmodified lines434435436437438439440441348 unmodified lines return None
def _is_comfyui_lora(state_dict) -> bool:
"""Whether a LoRA state dict is in ComfyUI's MiniMax-H3 naming rather than diffusers'.
ComfyUI names the block stack `blocks.N.*` and the token refiner `token_refiner.blocks.N.*`; diffusers names them
`transformer_blocks.N.*` and `token_refiner.refiner_blocks.N.*`. A key starting with `blocks.` is the tell.
"""
for key in state_dict:
if key.startswith(("blocks.", "token_refiner.blocks.", "final_layer.")):
return True
return False
def _convert_comfyui_lora(state_dict) -> dict:
"""Remap a ComfyUI-format MiniMax-H3 Turbo LoRA to the diffusers `transformer_ref` module names.
The Turbo LoRA ([`larryvrh/MiniMax-H3-Turbo-Lora`](https://huggingface.co/larryvrh/MiniMax-H3-Turbo-Lora)) is trained
against the ComfyUI checkpoint, whose module names differ from diffusers' in four ways:
* the block stack is `blocks.N` in ComfyUI but `transformer_blocks.N` in diffusers,
* the token refiner is `token_refiner.blocks.N` but `token_refiner.refiner_blocks.N`,
* the final AdaLN is `final_layer.adaln_proj.linear` but `norm_out.linear`,
* attention QKV is one fused `attn.qkv_proj` in ComfyUI but three separate `attn.to_q` / `to_k` / `to_v` in
diffusers, and the output projection is `attn.out_proj` but `attn.to_out.0`,
* the feed-forward is `mlp.fc1` / `mlp.fc2` but `ff.fc1` / `ff.fc2`.
The fused QKV `lora_B` is `[3 * inner_dim, rank]`; splitting it into three along dim 0 gives the three separate
`lora_B` matrices, and `lora_A` (which is `[rank, hidden_size]`) is shared verbatim across the three. The metadata
says `W_eff = W + lora_B @ lora_A` with alpha = rank, so the scaling is 1.0 and no alpha key is added.
"""
import torch
converted = {}
for key, value in state_dict.items():
# `blocks.N.` -> `transformer_blocks.N.`
if key.startswith("blocks."):
new_key = "transformer_blocks." + key[len("blocks."):]
elif key.startswith("token_refiner.blocks."):
new_key = "token_refiner.refiner_blocks." + key[len("token_refiner.blocks."):]
elif key.startswith("final_layer.adaln_proj.linear."):
new_key = "norm_out.linear." + key[len("final_layer.adaln_proj.linear."):]
else:
converted[key] = value
continue
# At this point `new_key` is a diffusers block path. Remap the leaf module names.
if ".attn.qkv_proj." in new_key:
# Fused QKV: split `lora_B` along dim 0 into q/k/v, duplicate `lora_A` verbatim.
leaf = new_key.split(".attn.qkv_proj.")[-1] # `lora_A.weight` or `lora_B.weight`
stem = new_key[: new_key.index(".attn.qkv_proj.")]
if leaf == "lora_A.weight":
for proj in ("to_q", "to_k", "to_v"):
converted[f"{stem}.attn.{proj}.lora_A.weight"] = value
else: # lora_B.weight
q_b, k_b, v_b = value.chunk(3, dim=0)
converted[f"{stem}.attn.to_q.lora_B.weight"] = q_b
converted[f"{stem}.attn.to_k.lora_B.weight"] = k_b
converted[f"{stem}.attn.to_v.lora_B.weight"] = v_b
elif ".attn.out_proj." in new_key:
converted[new_key.replace(".attn.out_proj.", ".attn.to_out.0.")] = value
elif ".mlp." in new_key:
converted[new_key.replace(".mlp.", ".ff.")] = value
else:
# `adaln_proj.linear` and the token refiner's attention/ff already match diffusers' names after the
# block-prefix rename above.
converted[new_key] = value
return converted
def apply_loras(transformer, loras) -> list[str]:
"""Attach `loras` (local path, strength) to `transformer` and give each its strength, replacing whatever was on it.
Every adapter already on the model is removed first, so a request is never affected by the one before it — which
matters when a worker is reused rather than forked fresh.
matters when a worker is reused rather than forked fresh. A LoRA in ComfyUI's MiniMax-H3 naming is remapped to
diffusers' module names on the fly, so the Turbo LoRA works without a separate conversion step.
"""
import torch
5 unmodified lines names, scales = [], []
for index, (path, scale) in enumerate(loras):
state_dict = load_file(path)
if _is_comfyui_lora(state_dict):
state_dict = _convert_comfyui_lora(state_dict)
name = f"lora{index}"
transformer.load_lora_adapter(state_dict, adapter_name=name, prefix=_lora_prefix(state_dict))
names.append(name)app.py+72-1