File size: 8,872 Bytes
2651102 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 | """
导出模型为JSON格式,用于WebGPU推理
"""
import os
import json
import argparse
import torch
import torch.nn as nn
import numpy as np
from typing import Dict, Any, List
from config import Config
from tokenizer import Tokenizer
from embedding import DualLanguageEmbedding, DualOutputProjection
from model import create_model
from diffusion import get_diffusion
def tensor_to_list(t) -> list:
"""将tensor转换为list"""
if isinstance(t, torch.Tensor):
return t.detach().cpu().numpy().tolist()
return t
def export_model(config: Config, checkpoint_path: str, output_dir: str):
"""导出模型为JSON格式"""
print(f"加载检查点: {checkpoint_path}")
state = torch.load(checkpoint_path, map_location="cpu", weights_only=False)
# 加载分词器
cache_dir = os.path.join(config.project_dir, config.data.cache_dir)
zh_tokenizer = Tokenizer.load(os.path.join(cache_dir, "tokenizer_zh.json"))
en_tokenizer = Tokenizer.load(os.path.join(cache_dir, "tokenizer_en.json"))
# 创建模型
embedding = DualLanguageEmbedding(
vocab_size_zh=zh_tokenizer.vocab_size_actual,
vocab_size_en=en_tokenizer.vocab_size_actual,
d_model=config.model.d_model,
max_len=config.model.max_len,
dropout=0.0,
)
output_proj = DualOutputProjection(
d_model=config.model.d_model,
vocab_size_zh=zh_tokenizer.vocab_size_actual,
vocab_size_en=en_tokenizer.vocab_size_actual,
)
model = create_model(config)
# 加载权重
embedding.load_state_dict(state['embedding'])
output_proj.load_state_dict(state['output_proj'])
model.load_state_dict(state['model'])
embedding.eval()
output_proj.eval()
model.eval()
# 创建输出目录
os.makedirs(output_dir, exist_ok=True)
# 导出扩散参数
diffusion, ddim_sampler = get_diffusion(config)
scheduler = diffusion.scheduler
diffusion_params = {
'timesteps': config.diffusion.timesteps,
'ddim_steps': config.diffusion.ddim_steps,
'betas': tensor_to_list(scheduler.betas),
'alphas': tensor_to_list(scheduler.alphas),
'alphas_cumprod': tensor_to_list(scheduler.alphas_cumprod),
'sqrt_alphas_cumprod': tensor_to_list(scheduler.sqrt_alphas_cumprod),
'sqrt_one_minus_alphas_cumprod': tensor_to_list(scheduler.sqrt_one_minus_alphas_cumprod),
'ddim_timesteps': ddim_sampler.ddim_timesteps,
}
with open(os.path.join(output_dir, 'diffusion_params.json'), 'w') as f:
json.dump(diffusion_params, f)
print("导出扩散参数完成")
# 导出分词器
zh_vocab = {
'token_to_id': zh_tokenizer.token_to_id,
'id_to_token': {str(k): v for k, v in zh_tokenizer.id_to_token.items()},
'merges': zh_tokenizer.merges,
'special_tokens': zh_tokenizer.special_tokens,
'lang': 'zh',
}
en_vocab = {
'token_to_id': en_tokenizer.token_to_id,
'id_to_token': {str(k): v for k, v in en_tokenizer.id_to_token.items()},
'merges': en_tokenizer.merges,
'special_tokens': en_tokenizer.special_tokens,
'lang': 'en',
}
with open(os.path.join(output_dir, 'tokenizer_zh.json'), 'w', encoding='utf-8') as f:
json.dump(zh_vocab, f, ensure_ascii=False)
with open(os.path.join(output_dir, 'tokenizer_en.json'), 'w', encoding='utf-8') as f:
json.dump(en_vocab, f, ensure_ascii=False)
print("导出分词器完成")
# 导出嵌入层权重为JSON
def extract_embedding_weights(lang_emb):
"""提取嵌入层权重"""
return {
'token_embedding': tensor_to_list(lang_emb.token_embedding.weight),
'position_encoding': tensor_to_list(lang_emb.position_encoding.pe),
'length_embedding': tensor_to_list(lang_emb.length_embedding.weight),
'scale': lang_emb.scale,
}
embedding_weights = {
'zh': extract_embedding_weights(embedding.zh_embedding),
'en': extract_embedding_weights(embedding.en_embedding),
}
with open(os.path.join(output_dir, 'embedding.json'), 'w') as f:
json.dump(embedding_weights, f)
print("导出嵌入层完成")
# 导出输出投影权重
output_weights = {
'zh_projection': tensor_to_list(output_proj.zh_projection.projection.weight),
'en_projection': tensor_to_list(output_proj.en_projection.projection.weight),
}
with open(os.path.join(output_dir, 'output_proj.json'), 'w') as f:
json.dump(output_weights, f)
print("导出输出投影完成")
# 导出噪声预测模型权重
def extract_model_weights(model):
"""提取模型权重"""
weights = {}
# 时间嵌入
weights['time_mlp'] = {
'0.weight': tensor_to_list(model.time_mlp[0].weight),
'0.bias': tensor_to_list(model.time_mlp[0].bias),
'2.weight': tensor_to_list(model.time_mlp[2].weight),
'2.bias': tensor_to_list(model.time_mlp[2].bias),
}
# 语言特定投影
weights['zh_input_proj'] = {
'weight': tensor_to_list(model.zh_input_proj.weight),
'bias': tensor_to_list(model.zh_input_proj.bias),
}
weights['en_input_proj'] = {
'weight': tensor_to_list(model.en_input_proj.weight),
'bias': tensor_to_list(model.en_input_proj.bias),
}
weights['zh_output_proj'] = {
'weight': tensor_to_list(model.zh_output_proj.weight),
'bias': tensor_to_list(model.zh_output_proj.bias),
}
weights['en_output_proj'] = {
'weight': tensor_to_list(model.en_output_proj.weight),
'bias': tensor_to_list(model.en_output_proj.bias),
}
# 输出归一化
weights['output_norm'] = {
'weight': tensor_to_list(model.output_norm.weight),
'bias': tensor_to_list(model.output_norm.bias),
}
# Transformer层
weights['layers'] = []
for i, layer in enumerate(model.layers):
layer_weights = {
# 自注意力
'w_q.weight': tensor_to_list(layer.attn.w_q.weight),
'w_q.bias': tensor_to_list(layer.attn.w_q.bias),
'w_k.weight': tensor_to_list(layer.attn.w_k.weight),
'w_k.bias': tensor_to_list(layer.attn.w_k.bias),
'w_v.weight': tensor_to_list(layer.attn.w_v.weight),
'w_v.bias': tensor_to_list(layer.attn.w_v.bias),
'w_o.weight': tensor_to_list(layer.attn.w_o.weight),
'w_o.bias': tensor_to_list(layer.attn.w_o.bias),
# 前馈网络
'w1.weight': tensor_to_list(layer.ff.w1.weight),
'w1.bias': tensor_to_list(layer.ff.w1.bias),
'w2.weight': tensor_to_list(layer.ff.w2.weight),
'w2.bias': tensor_to_list(layer.ff.w2.bias),
# LayerNorm
'norm1.weight': tensor_to_list(layer.norm1.weight),
'norm1.bias': tensor_to_list(layer.norm1.bias),
'norm2.weight': tensor_to_list(layer.norm2.weight),
'norm2.bias': tensor_to_list(layer.norm2.bias),
}
weights['layers'].append(layer_weights)
return weights
model_weights = extract_model_weights(model)
with open(os.path.join(output_dir, 'model.json'), 'w') as f:
json.dump(model_weights, f)
print("导出模型权重完成")
# 导出配置
config_dict = {
'd_model': config.model.d_model,
'n_heads': config.model.n_heads,
'n_layers': config.model.n_layers,
'd_ff': config.model.d_ff,
'max_len': config.model.max_len,
'vocab_size_zh': zh_tokenizer.vocab_size_actual,
'vocab_size_en': en_tokenizer.vocab_size_actual,
}
with open(os.path.join(output_dir, 'config.json'), 'w') as f:
json.dump(config_dict, f)
print(f"\n导出完成! 文件保存在: {output_dir}")
print("文件列表:")
for f in os.listdir(output_dir):
path = os.path.join(output_dir, f)
size = os.path.getsize(path) / 1024 / 1024
print(f" {f}: {size:.2f} MB")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="导出模型为JSON格式")
parser.add_argument("--checkpoint", type=str, default="checkpoints/best.pt", help="检查点路径")
parser.add_argument("--output", type=str, default="web/models", help="输出目录")
args = parser.parse_args()
config = Config()
export_model(config, args.checkpoint, args.output)
|