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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import argparse
|
| 3 |
+
import json
|
| 4 |
+
import torch
|
| 5 |
+
import numpy as np
|
| 6 |
+
import mlx.core as mx
|
| 7 |
+
import mlx.nn as nn
|
| 8 |
+
import mlx.utils
|
| 9 |
+
from safetensors.torch import load_file as load_pt_file
|
| 10 |
+
from mlx_z_image import ZImageTransformerMLX
|
| 11 |
+
from tqdm import tqdm
|
| 12 |
+
|
| 13 |
+
# From https://huggingface.co/Tongyi-MAI/Z-Image-Turbo/blob/main/transformer/config.json
|
| 14 |
+
config = {
|
| 15 |
+
"_class_name": "ZImageTransformer2DModel",
|
| 16 |
+
"_diffusers_version": "0.36.0.dev0",
|
| 17 |
+
"all_f_patch_size": [1],
|
| 18 |
+
"all_patch_size": [2],
|
| 19 |
+
"axes_dims": [32, 48, 48],
|
| 20 |
+
"axes_lens": [1536, 512, 512],
|
| 21 |
+
"cap_feat_dim": 2560,
|
| 22 |
+
"dim": 3840,
|
| 23 |
+
"in_channels": 16,
|
| 24 |
+
"n_heads": 30,
|
| 25 |
+
"n_kv_heads": 30,
|
| 26 |
+
"n_layers": 30,
|
| 27 |
+
"n_refiner_layers": 2,
|
| 28 |
+
"norm_eps": 1e-05,
|
| 29 |
+
"qk_norm": True,
|
| 30 |
+
"rope_theta": 256.0,
|
| 31 |
+
"t_scale": 1000.0,
|
| 32 |
+
"nheads": 30,
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
# Helpers functions to revert ComfyUI single file model to diffusers format state_dict
|
| 37 |
+
# Some keys are already in the target naming, but i'll revert them nonetheless to use
|
| 38 |
+
# the original code as-is. Undo what is done here:
|
| 39 |
+
# https://huggingface.co/Comfy-Org/z_image_turbo/blob/main/z_image_convert_original_to_comfy.py
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
# remove prefix
|
| 43 |
+
def remove_prefix(key):
|
| 44 |
+
if key.startswith("model.diffusion_model."):
|
| 45 |
+
return key.replace("model.diffusion_model.", "")
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
# split qkv layers into q,k and v layers
|
| 49 |
+
def remap_qkv(key, state_dict):
|
| 50 |
+
weight = state_dict.pop(key)
|
| 51 |
+
to_q, to_k, to_v = weight.chunk(3, dim=0)
|
| 52 |
+
state_dict[remove_prefix(key).replace(".qkv.", ".to_q.")] = to_q
|
| 53 |
+
state_dict[remove_prefix(key).replace(".qkv.", ".to_k.")] = to_k
|
| 54 |
+
state_dict[remove_prefix(key).replace(".qkv.", ".to_v.")] = to_v
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
replace_keys = {
|
| 58 |
+
"final_layer.": "all_final_layer.2-1.",
|
| 59 |
+
"x_embedder.": "all_x_embedder.2-1.",
|
| 60 |
+
".attention.out.bias": ".attention.to_out.0.bias",
|
| 61 |
+
".attention.k_norm.weight": ".attention.norm_k.weight",
|
| 62 |
+
".attention.q_norm.weight": ".attention.norm_q.weight",
|
| 63 |
+
".attention.out.weight": ".attention.to_out.0.weight",
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
# restore original name of keys
|
| 68 |
+
def remap_keys(key, state_dict):
|
| 69 |
+
new_key = remove_prefix(key)
|
| 70 |
+
for r, rr in replace_keys.items():
|
| 71 |
+
new_key = new_key.replace(r, rr)
|
| 72 |
+
state_dict[new_key] = state_dict.pop(key)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
# Torch to MLX converter function from https://github.com/uqer1244/MLX_z-image/blob/master/converting/convert.py
|
| 76 |
+
def map_key_and_convert(key, tensor):
|
| 77 |
+
# PyTorch Tensor -> Numpy (Float32)
|
| 78 |
+
# BF16 변환은 나중에 MLX array 생성 시 수행
|
| 79 |
+
if isinstance(tensor, torch.Tensor):
|
| 80 |
+
val = tensor.detach().cpu().float().numpy()
|
| 81 |
+
else:
|
| 82 |
+
val = tensor
|
| 83 |
+
|
| 84 |
+
new_key = key
|
| 85 |
+
|
| 86 |
+
# 키 매핑 로직 (기존과 동일)
|
| 87 |
+
if "t_embedder.mlp.0" in key:
|
| 88 |
+
new_key = key.replace("t_embedder.mlp.0", "t_embedder.linear1")
|
| 89 |
+
elif "t_embedder.mlp.2" in key:
|
| 90 |
+
new_key = key.replace("t_embedder.mlp.2", "t_embedder.linear2")
|
| 91 |
+
elif "all_x_embedder.2-1" in key:
|
| 92 |
+
new_key = key.replace("all_x_embedder.2-1", "x_embedder")
|
| 93 |
+
elif "cap_embedder.0" in key:
|
| 94 |
+
new_key = key.replace("cap_embedder.0", "cap_embedder.layers.0")
|
| 95 |
+
elif "cap_embedder.1" in key:
|
| 96 |
+
new_key = key.replace("cap_embedder.1", "cap_embedder.layers.1")
|
| 97 |
+
elif "all_final_layer.2-1" in key:
|
| 98 |
+
new_key = key.replace("all_final_layer.2-1", "final_layer")
|
| 99 |
+
|
| 100 |
+
if "adaLN_modulation.1" in new_key:
|
| 101 |
+
new_key = new_key.replace("adaLN_modulation.1", "adaLN_modulation.layers.1")
|
| 102 |
+
elif "attention.to_out.0" in key:
|
| 103 |
+
new_key = key.replace("attention.to_out.0", "attention.to_out")
|
| 104 |
+
elif "adaLN_modulation.0" in key and "final" not in key:
|
| 105 |
+
new_key = key.replace("adaLN_modulation.0", "adaLN_modulation")
|
| 106 |
+
elif "adaLN_modulation.1" in key and "final" not in key:
|
| 107 |
+
new_key = key.replace("adaLN_modulation.1", "adaLN_modulation")
|
| 108 |
+
|
| 109 |
+
# Changed to a tuple from original code to allow loading without saving to disk
|
| 110 |
+
return (new_key, mx.array(val).astype(mx.bfloat16))
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def main():
|
| 114 |
+
parser = argparse.ArgumentParser(
|
| 115 |
+
description="Convert and Quantize ZIT AIO safetensors to MLX model in 4-bit"
|
| 116 |
+
)
|
| 117 |
+
parser.add_argument(
|
| 118 |
+
"--src_model",
|
| 119 |
+
type=str,
|
| 120 |
+
default="comfy.safetensors",
|
| 121 |
+
help="Path to ZIT model in ComfyUI format",
|
| 122 |
+
)
|
| 123 |
+
parser.add_argument(
|
| 124 |
+
"--dst_model",
|
| 125 |
+
type=str,
|
| 126 |
+
default="mlx.safetensors",
|
| 127 |
+
help="Path to save quantized model in mlx format",
|
| 128 |
+
)
|
| 129 |
+
parser.add_argument(
|
| 130 |
+
"--lora_model",
|
| 131 |
+
type=str,
|
| 132 |
+
default="",
|
| 133 |
+
help="Path to an optional LoRA to merge during conversion",
|
| 134 |
+
)
|
| 135 |
+
parser.add_argument(
|
| 136 |
+
"--lora_scale", type=float, default=1.0, help="Scale for the optional LoRA"
|
| 137 |
+
)
|
| 138 |
+
parser.add_argument(
|
| 139 |
+
"--group_size", type=int, default=32, help="Group size for quantization"
|
| 140 |
+
)
|
| 141 |
+
args = parser.parse_args()
|
| 142 |
+
|
| 143 |
+
print("Starting conversion!")
|
| 144 |
+
|
| 145 |
+
print(f"Loading {args.src_model} file...")
|
| 146 |
+
|
| 147 |
+
pt_weights = load_pt_file(args.src_model)
|
| 148 |
+
|
| 149 |
+
# Remove an unexpected key. TODO: figure out from where it cames.
|
| 150 |
+
if "model.diffusion_model.norm_final.weight" in pt_weights.keys():
|
| 151 |
+
del pt_weights["model.diffusion_model.norm_final.weight"]
|
| 152 |
+
|
| 153 |
+
print("Reverting ComfyUI format...")
|
| 154 |
+
|
| 155 |
+
keys = list(pt_weights.keys())
|
| 156 |
+
|
| 157 |
+
for k in tqdm(keys):
|
| 158 |
+
if ".qkv." in k:
|
| 159 |
+
remap_qkv(k, pt_weights)
|
| 160 |
+
else:
|
| 161 |
+
remap_keys(k, pt_weights)
|
| 162 |
+
|
| 163 |
+
if args.lora_model:
|
| 164 |
+
counter = 0
|
| 165 |
+
print(f"Merging LoRA {args.lora_model} at scale {args.lora_scale}...")
|
| 166 |
+
|
| 167 |
+
lora_weights = load_pt_file(args.lora_model)
|
| 168 |
+
keys = [k for k in pt_weights.keys() if k.endswith(".weight")]
|
| 169 |
+
|
| 170 |
+
for k in tqdm(keys):
|
| 171 |
+
down_key = f"diffusion_model.{k}".replace(".weight", ".lora_A.weight")
|
| 172 |
+
up_key = f"diffusion_model.{k}".replace(".weight", ".lora_B.weight")
|
| 173 |
+
if down_key in lora_weights.keys() and up_key in lora_weights.keys():
|
| 174 |
+
counter += 1
|
| 175 |
+
pt_weights[k] = pt_weights[k] + args.lora_scale * (
|
| 176 |
+
lora_weights[up_key] @ lora_weights[down_key]
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
print(f"Merged {counter} weight keys")
|
| 180 |
+
|
| 181 |
+
print("Converting to MLX...")
|
| 182 |
+
|
| 183 |
+
mlx_weights = []
|
| 184 |
+
|
| 185 |
+
for k, v in tqdm(pt_weights.items()):
|
| 186 |
+
mlx_weights.append(map_key_and_convert(k, v))
|
| 187 |
+
|
| 188 |
+
print("Loading converted weights...")
|
| 189 |
+
|
| 190 |
+
model = ZImageTransformerMLX(config)
|
| 191 |
+
model.load_weights(mlx_weights)
|
| 192 |
+
|
| 193 |
+
print(f"Quantizing (bits=4, group_size={args.group_size})...")
|
| 194 |
+
|
| 195 |
+
nn.quantize(model, bits=4, group_size=args.group_size)
|
| 196 |
+
|
| 197 |
+
print(f"Saving {args.dst_model} file...")
|
| 198 |
+
|
| 199 |
+
quant_weights = dict(mlx.utils.tree_flatten(model.parameters()))
|
| 200 |
+
mx.save_safetensors(args.dst_model, quant_weights)
|
| 201 |
+
|
| 202 |
+
print("Done!")
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
if __name__ == "__main__":
|
| 206 |
+
main()
|