Upload 2 files
Browse files
sam3/scripts/convert_pt_to_fp8.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import argparse
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
def convert_pt_to_fp8(input_file, output_file):
|
| 6 |
+
try:
|
| 7 |
+
# 获取当前运行目录的绝对路径,锁定范围
|
| 8 |
+
current_dir = os.getcwd()
|
| 9 |
+
|
| 10 |
+
in_path = os.path.abspath(os.path.join(current_dir, input_file))
|
| 11 |
+
out_path = os.path.abspath(os.path.join(current_dir, output_file))
|
| 12 |
+
|
| 13 |
+
# 严格限制:只允许处理当前目录下的文件
|
| 14 |
+
if os.path.dirname(in_path) != current_dir or os.path.dirname(out_path) != current_dir:
|
| 15 |
+
print("❌ 错误:基于安全限制,本脚本只允许处理当前目录下的文件!")
|
| 16 |
+
return
|
| 17 |
+
|
| 18 |
+
if not os.path.exists(in_path):
|
| 19 |
+
print(f"❌ 错误:找不到输入文件 '{input_file}'")
|
| 20 |
+
return
|
| 21 |
+
|
| 22 |
+
print(f"📦 正在加载 FP16 模型权重: {input_file} ...")
|
| 23 |
+
# 视你的硬件情况,可将 map_location 设为 'cuda' 或 'cpu'
|
| 24 |
+
state_dict = torch.load(in_path, map_location='cpu')
|
| 25 |
+
|
| 26 |
+
print("⚡ 正在将浮点数转换为底层 FP8 (E4M3FN) 格式...")
|
| 27 |
+
fp8_state_dict = {}
|
| 28 |
+
|
| 29 |
+
# 判断载入的是直接的 OrderedDict 还是包裹在字典里的权重
|
| 30 |
+
if isinstance(state_dict, dict) and 'model' in state_dict:
|
| 31 |
+
target_dict = state_dict['model']
|
| 32 |
+
is_wrapped = True
|
| 33 |
+
else:
|
| 34 |
+
target_dict = state_dict
|
| 35 |
+
is_wrapped = False
|
| 36 |
+
|
| 37 |
+
for k, v in target_dict.items():
|
| 38 |
+
if isinstance(v, torch.Tensor):
|
| 39 |
+
# 只有浮点数(FP32/FP16)需要转为 FP8,整数(如层索引、形状)原样保留
|
| 40 |
+
if v.is_floating_point():
|
| 41 |
+
# 转换为 PyTorch 标准的 FP8 权重存储格式
|
| 42 |
+
fp8_state_dict[k] = v.to(dtype=torch.float8_e4m3fn)
|
| 43 |
+
else:
|
| 44 |
+
fp8_state_dict[k] = v
|
| 45 |
+
else:
|
| 46 |
+
fp8_state_dict[k] = v
|
| 47 |
+
|
| 48 |
+
# 保持原有的包裹外壳结构
|
| 49 |
+
output_data = {'model': fp8_state_dict} if is_wrapped else fp8_state_dict
|
| 50 |
+
|
| 51 |
+
print(f"💾 正在保存 FP8 模型至: {output_file} ...")
|
| 52 |
+
torch.save(output_data, out_path)
|
| 53 |
+
print(f"✅ 成功生成 FP8 权重文件!")
|
| 54 |
+
|
| 55 |
+
except Exception as e:
|
| 56 |
+
print(f"❌ 转换失败,错误原因: {e}")
|
| 57 |
+
|
| 58 |
+
if __name__ == "__main__":
|
| 59 |
+
parser = argparse.ArgumentParser(description="将 FP16/FP32 的 .pt 权重转换为 FP8(E4M3) 格式(仅限当前目录)")
|
| 60 |
+
parser.add_argument("-i", "--input", required=True, help="输入的 .pt 权重文件名")
|
| 61 |
+
parser.add_argument("-o", "--output", required=True, help="输出的 FP8 .pt 文件名")
|
| 62 |
+
|
| 63 |
+
args = parser.parse_args()
|
| 64 |
+
convert_pt_to_fp8(args.input, args.output)
|
sam3/scripts/convert_pt_to_mixed_fp8_sam3only.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import argparse
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
def convert_to_sam3_mixed_fp8(input_file, output_file):
|
| 6 |
+
try:
|
| 7 |
+
# 1. 严格锁定当前目录
|
| 8 |
+
current_dir = os.getcwd()
|
| 9 |
+
in_path = os.path.abspath(os.path.join(current_dir, input_file))
|
| 10 |
+
out_path = os.path.abspath(os.path.join(current_dir, output_file))
|
| 11 |
+
|
| 12 |
+
if os.path.dirname(in_path) != current_dir or os.path.dirname(out_path) != current_dir:
|
| 13 |
+
print("❌ 错误:基于安全限制,本脚本只允许处理当前目录下的文件!")
|
| 14 |
+
return
|
| 15 |
+
|
| 16 |
+
if not os.path.exists(in_path):
|
| 17 |
+
print(f"❌ 错误:找不到输入文件 '{input_file}'")
|
| 18 |
+
return
|
| 19 |
+
|
| 20 |
+
print(f"📦 正在加载原始高精度模型: {input_file} ...")
|
| 21 |
+
state_dict = torch.load(in_path, map_location='cpu')
|
| 22 |
+
|
| 23 |
+
print("⚡ 正在根据您的 SAM3 专属层列表,执行 FP8 / FP16 混合量化...")
|
| 24 |
+
mixed_state_dict = {}
|
| 25 |
+
|
| 26 |
+
# 结构包裹处理
|
| 27 |
+
if isinstance(state_dict, dict) and 'model' in state_dict:
|
| 28 |
+
target_dict = state_dict['model']
|
| 29 |
+
is_wrapped = True
|
| 30 |
+
else:
|
| 31 |
+
target_dict = state_dict
|
| 32 |
+
is_wrapped = False
|
| 33 |
+
|
| 34 |
+
# --- 🎯 混合精度映射核心策略 ---
|
| 35 |
+
# 1. 绝对强制留守 FP16 的黑名单(包含复数编码、偏置、非矩阵层和核心输出层)
|
| 36 |
+
fp16_forced_keywords = [
|
| 37 |
+
"bias", "norm", "ln_", "freqs_cis", "pos_embed", "embedding",
|
| 38 |
+
"reference_points", "bbox_embed", "boxrpb_embed", "presence_token",
|
| 39 |
+
"semantic_seg_head", "instance_seg_head", "gamma", "gaussian_matrix"
|
| 40 |
+
]
|
| 41 |
+
|
| 42 |
+
# 2. 优先允许降级为 FP8 的核心大矩阵白名单
|
| 43 |
+
fp8_target_keywords = [
|
| 44 |
+
"qkv", "q_proj", "k_proj", "v_proj", "out_proj", "in_proj",
|
| 45 |
+
"fc1", "fc2", "linear1", "linear2", "pwconv", "proj.weight",
|
| 46 |
+
"prompt_mlp", "hs_proj", "mask_embed", "hypernetworks_mlps"
|
| 47 |
+
]
|
| 48 |
+
|
| 49 |
+
fp8_count = 0
|
| 50 |
+
fp16_count = 0
|
| 51 |
+
skipped_count = 0
|
| 52 |
+
|
| 53 |
+
for k, v in target_dict.items():
|
| 54 |
+
if isinstance(v, torch.Tensor):
|
| 55 |
+
k_lower = k.lower()
|
| 56 |
+
|
| 57 |
+
# 只有浮点类型才考虑转精度
|
| 58 |
+
if v.is_floating_point():
|
| 59 |
+
# 规则 A: 如果命中了死守 FP16 的核心层关键词 -> FP16
|
| 60 |
+
is_forced_fp16 = any(w in k_lower for w in fp16_forced_keywords)
|
| 61 |
+
# 规则 B: 检查是否属于适合转为 FP8 的大矩阵 -> FP8
|
| 62 |
+
is_target_fp8 = any(w in k_lower for w in fp8_target_keywords)
|
| 63 |
+
|
| 64 |
+
if is_target_fp8 and not is_forced_fp16:
|
| 65 |
+
# 核心计算大矩阵:安全降级至 FP8 (E4M3FN)
|
| 66 |
+
mixed_state_dict[k] = v.to(dtype=torch.float8_e4m3fn)
|
| 67 |
+
fp8_count += 1
|
| 68 |
+
else:
|
| 69 |
+
# 敏感或边缘控制层:降级保留至高精度的 FP16
|
| 70 |
+
mixed_state_dict[k] = v.to(dtype=torch.float16)
|
| 71 |
+
fp16_count += 1
|
| 72 |
+
else:
|
| 73 |
+
# 诸如 complex64 复数等非普通浮点数据类型,原封不动保留
|
| 74 |
+
mixed_state_dict[k] = v
|
| 75 |
+
skipped_count += 1
|
| 76 |
+
else:
|
| 77 |
+
mixed_state_dict[k] = v
|
| 78 |
+
skipped_count += 1
|
| 79 |
+
|
| 80 |
+
output_data = {'model': mixed_state_dict} if is_wrapped else mixed_state_dict
|
| 81 |
+
|
| 82 |
+
print(f"\n📊 混合量化分配报告:")
|
| 83 |
+
print(f" - ⚡ 完美转换为 FP8 的大计算量矩阵层数: {fp8_count}")
|
| 84 |
+
print(f" - 🔒 安全保留为 FP16 高精度的敏感结构层数: {fp16_count}")
|
| 85 |
+
print(f" - 🛠️ 跳过不作处理的特殊类型/非张量层数: {skipped_count}")
|
| 86 |
+
|
| 87 |
+
print(f"\n💾 正在保存混合精度模型至: {output_file} ...")
|
| 88 |
+
torch.save(output_data, out_path)
|
| 89 |
+
print(f"✅ 转换大功告成!生成的混合精度模型已可进行测试。")
|
| 90 |
+
|
| 91 |
+
except Exception as e:
|
| 92 |
+
print(f"❌ 转换过程中发生未预期中断,错误原因: {e}")
|
| 93 |
+
|
| 94 |
+
if __name__ == "__main__":
|
| 95 |
+
parser = argparse.ArgumentParser(description="根据真实列表定制的 SAM3 混合精度转换工具")
|
| 96 |
+
parser.add_argument("-i", "--input", required=True, help="输入的 FP32 权重文件名")
|
| 97 |
+
parser.add_argument("-o", "--output", required=True, help="输出的混合精度文件名")
|
| 98 |
+
|
| 99 |
+
args = parser.parse_args()
|
| 100 |
+
convert_to_sam3_mixed_fp8(args.input, args.output)
|