loras_tools / checkpoint_splitter /checkpoint_int8_convrot.py
waveshaker's picture
Upload 7 files
9f09426 verified
Raw History Blame Contribute Delete
4.66 kB
import os
import sys
import subprocess
from safetensors import safe_open
from safetensors.torch import save_file
def run_pipeline(input_path, output_path=None):
if not os.path.exists(input_path):
print(f"❌ 错误: 找不到输入模型 '{input_path}'")
return
if not output_path:
base_dir = os.path.dirname(input_path)
base_name = os.path.splitext(os.path.basename(input_path))[0]
if not base_name.endswith("_qic_int8_convrot"):
output_path = os.path.join(base_dir, f"{base_name}_qic_int8_convrot.safetensors")
else:
output_path = os.path.join(base_dir, f"{base_name}.safetensors")
print(f"🎯 目标输出文件: {output_path}")
base_dir = os.path.dirname(input_path)
tmp_unet_fp16 = os.path.join(base_dir, "tmp_unet_fp16.safetensors")
tmp_unet_int8 = os.path.join(base_dir, "tmp_unet_int8.safetensors")
tmp_other = os.path.join(base_dir, "tmp_clip_vae_extras.safetensors")
quant_script = os.path.join(os.path.dirname(os.path.abspath(__file__)), "quant_int8_convrot.py")
try:
# ==========================================
# 步骤 1:黑盒拆离
# ==========================================
print("\n📦 [1/3] 正在拆离模型...")
unet_dict = {}
other_dict = {}
with safe_open(input_path, framework="pt", device="cpu") as f:
for key in f.keys():
if key.startswith("model.diffusion_model."):
clean_key = key.replace("model.diffusion_model.", "", 1)
unet_dict[clean_key] = f.get_tensor(key)
else:
# 💡 重点修改:把 CLIP, VAE, 甚至 model_ema, lora 等全部收集起来
other_dict[key] = f.get_tensor(key)
if not unet_dict:
print("❌ 错误: 未在模型中找到 UNet (model.diffusion_model.),任务终止。")
return
save_file(unet_dict, tmp_unet_fp16)
save_file(other_dict, tmp_other)
print(f" --> ✅ 拆离完成。UNet 键数: {len(unet_dict)}, 其他组件键数: {len(other_dict)}")
# ==========================================
# 步骤 2:量化
# ==========================================
print("\n⚙️ [2/3] 正在调用量化脚本 (Int8 ConvRot)...")
cmd = [sys.executable, quant_script, tmp_unet_fp16, tmp_unet_int8, "--mseclip"]
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
for line in process.stdout:
print(line, end="")
process.wait()
if process.returncode != 0:
print("\n❌ 错误: 量化脚本执行失败!")
return
print(" --> ✅ 量化完成。")
# ==========================================
# 步骤 3:重组
# ==========================================
print("\n🔗 [3/3] 正在重组大模型 (Merge)...")
final_dict = {}
# 加入量化后的 UNet
with safe_open(tmp_unet_int8, framework="pt", device="cpu") as f:
for key in f.keys():
if not key.startswith("model.diffusion_model."):
new_key = f"model.diffusion_model.{key}"
else:
new_key = key
final_dict[new_key] = f.get_tensor(key)
# 把收集起来的其他组件(CLIP, VAE, 甚至 EMA)原样塞回去
with safe_open(tmp_other, framework="pt", device="cpu") as f:
for key in f.keys():
final_dict[key] = f.get_tensor(key)
save_file(final_dict, output_path)
print(f" --> 🎉 重组成功!总键数: {len(final_dict)}")
print(f" --> 🎉 最终文件已保存至: {output_path}")
except Exception as e:
print(f"\n❌ 发生异常: {e}")
finally:
print("\n🧹 正在清理临时文件...")
for tmp_file in [tmp_unet_fp16, tmp_unet_int8, tmp_other]:
if os.path.exists(tmp_file):
os.remove(tmp_file)
print(" --> ✅ 清理完毕。")
if __name__ == "__main__":
if len(sys.argv) < 2 or len(sys.argv) > 3:
print("💡 用法: python checkpoint_int8_convrot.py <原版大模型.safetensors> [最终输出大模型.safetensors]")
sys.exit(1)
src_file = sys.argv[1]
dst_file = sys.argv[2] if len(sys.argv) == 3 else None
run_pipeline(src_file, dst_file)