aifeifei798 commited on
Commit
b826c86
·
verified ·
1 Parent(s): 7df8a77

Upload fix_fp16_lora.py

Browse files
Files changed (1) hide show
  1. fix_fp16_lora.py +53 -0
fix_fp16_lora.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from safetensors.torch import load_file, save_file
3
+ import os
4
+
5
+ # --- ⚙️ 在这里配置 ---
6
+
7
+ # 1. 指向你那个有问题的、旧的 LoRA 文件
8
+ # (就是你之前训练 Z-Image LoRA 时生成的那个)
9
+ OLD_LORA_FILE = "./Turbo_Booster_v1.safetensors" # 示例路径,请替换成你的
10
+
11
+ # 2. 定义新文件的保存路径和名字
12
+ NEW_LORA_FILE = "Turbo_Booster_v1-fp16.safetensors"
13
+
14
+ # 3. 目标精度 (fp16 兼容性最好)
15
+ TARGET_DTYPE = torch.float16
16
+
17
+ # --- 配置结束 ---
18
+
19
+ def fix_lora_precision():
20
+ if not os.path.exists(OLD_LORA_FILE):
21
+ print(f"❌ 错误: 找不到旧的 LoRA 文件: {OLD_LORA_FILE}")
22
+ return
23
+
24
+ print(f"✅ 正在从 '{OLD_LORA_FILE}' 加载权重...")
25
+ try:
26
+ state_dict = load_file(OLD_LORA_FILE)
27
+ print(f" - 成功加载 {len(state_dict)} 个权重张量。")
28
+ except Exception as e:
29
+ print(f"❌ 加载权重时出错: {e}")
30
+ return
31
+
32
+ # 检查一下第一个权重的数据类型,确认它确实是 fp32
33
+ first_key = next(iter(state_dict))
34
+ if state_dict[first_key].dtype != torch.float32:
35
+ print(f"⚠️ 警告: 权重似乎不是 fp32 格式 (检测到 {state_dict[first_key].dtype})。脚本仍会继续转换。")
36
+
37
+ new_state_dict = {}
38
+ print(f"\n🔄 正在将所有权重转换为 {TARGET_DTYPE}...")
39
+
40
+ for key, tensor in state_dict.items():
41
+ new_state_dict[key] = tensor.to(TARGET_DTYPE)
42
+
43
+ print(f"\n💾 正在将转换后的权重保存到 '{NEW_LORA_FILE}'...")
44
+ try:
45
+ save_file(new_state_dict, NEW_LORA_FILE)
46
+ print("\n✨ 修复完成!")
47
+ print(f" - 新的、与 fp8 兼容的 LoRA 文件已保存在: {NEW_LORA_FILE}")
48
+ print(" - 你现在可以把这个新文件重命名为 'pytorch_lora_weights.safetensors' 并上传更新了。")
49
+ except Exception as e:
50
+ print(f"❌ 保存新文件时出错: {e}")
51
+
52
+ if __name__ == "__main__":
53
+ fix_lora_precision()