convert_model.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. import os
  2. import sys
  3. import json
  4. __package__ = "scripts"
  5. sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
  6. import torch
  7. import transformers
  8. import warnings
  9. from transformers import AutoTokenizer, AutoModelForCausalLM, Qwen3Config, Qwen3ForCausalLM, Qwen3MoeConfig, Qwen3MoeForCausalLM
  10. from model.model_minimind import MiniMindConfig, MiniMindForCausalLM
  11. from model.model_lora import apply_lora, merge_lora
  12. warnings.filterwarnings('ignore', category=UserWarning)
  13. def convert_torch2transformers_minimind(torch_path, transformers_path, dtype=torch.float16):
  14. MiniMindConfig.register_for_auto_class()
  15. MiniMindForCausalLM.register_for_auto_class("AutoModelForCausalLM")
  16. lm_model = MiniMindForCausalLM(lm_config)
  17. device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
  18. state_dict = torch.load(torch_path, map_location=device)
  19. lm_model.load_state_dict(state_dict, strict=False)
  20. lm_model = lm_model.to(dtype) # 转换模型权重精度
  21. model_params = sum(p.numel() for p in lm_model.parameters() if p.requires_grad)
  22. print(f'模型参数: {model_params / 1e6} 百万 = {model_params / 1e9} B (Billion)')
  23. lm_model.save_pretrained(transformers_path, safe_serialization=False)
  24. tokenizer = AutoTokenizer.from_pretrained('../model/')
  25. tokenizer.save_pretrained(transformers_path)
  26. # ======= transformers-5.0的兼容低版本写法 =======
  27. if int(transformers.__version__.split('.')[0]) >= 5:
  28. tokenizer_config_path, config_path = os.path.join(transformers_path, "tokenizer_config.json"), os.path.join(transformers_path, "config.json")
  29. json.dump({**json.load(open(tokenizer_config_path, 'r', encoding='utf-8')), "tokenizer_class": "PreTrainedTokenizerFast", "extra_special_tokens": {}}, open(tokenizer_config_path, 'w', encoding='utf-8'), indent=2, ensure_ascii=False)
  30. config = json.load(open(config_path, 'r', encoding='utf-8'))
  31. config['rope_theta'] = lm_config.rope_theta; config['rope_scaling'] = None; del config['rope_parameters']
  32. json.dump(config, open(config_path, 'w', encoding='utf-8'), indent=2, ensure_ascii=False)
  33. print(f"模型已保存为 Transformers-MiniMind 格式: {transformers_path}")
  34. # QwenForCausalLM/LlamaForCausalLM结构兼容生态
  35. def convert_torch2transformers(torch_path, transformers_path, dtype=torch.float16):
  36. device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
  37. state_dict = torch.load(torch_path, map_location=device)
  38. common_config = {
  39. "vocab_size": lm_config.vocab_size,
  40. "hidden_size": lm_config.hidden_size,
  41. "intermediate_size": lm_config.intermediate_size,
  42. "num_hidden_layers": lm_config.num_hidden_layers,
  43. "num_attention_heads": lm_config.num_attention_heads,
  44. "num_key_value_heads": lm_config.num_key_value_heads,
  45. "head_dim": lm_config.hidden_size // lm_config.num_attention_heads,
  46. "max_position_embeddings": lm_config.max_position_embeddings,
  47. "rms_norm_eps": lm_config.rms_norm_eps,
  48. "rope_theta": lm_config.rope_theta,
  49. "tie_word_embeddings": True
  50. }
  51. if not lm_config.use_moe:
  52. qwen_config = Qwen3Config(
  53. **common_config,
  54. use_sliding_window=False,
  55. sliding_window=None
  56. )
  57. qwen_model = Qwen3ForCausalLM(qwen_config)
  58. else:
  59. qwen_config = Qwen3MoeConfig(
  60. **common_config,
  61. num_experts=lm_config.num_experts,
  62. num_experts_per_tok=lm_config.num_experts_per_tok,
  63. moe_intermediate_size=lm_config.moe_intermediate_size,
  64. norm_topk_prob=lm_config.norm_topk_prob
  65. )
  66. qwen_model = Qwen3MoeForCausalLM(qwen_config)
  67. # ======= transformers-5.0的兼容低版本写法 =======
  68. if int(transformers.__version__.split('.')[0]) >= 5:
  69. new_sd = {k: v for k, v in state_dict.items() if 'experts.' not in k or 'gate.weight' in k}
  70. for l in range(lm_config.num_hidden_layers):
  71. p = f'model.layers.{l}.mlp.experts'
  72. new_sd[f'{p}.gate_up_proj'] = torch.cat([torch.stack([state_dict[f'{p}.{e}.gate_proj.weight'] for e in range(lm_config.num_experts)]), torch.stack([state_dict[f'{p}.{e}.up_proj.weight'] for e in range(lm_config.num_experts)])], dim=1)
  73. new_sd[f'{p}.down_proj'] = torch.stack([state_dict[f'{p}.{e}.down_proj.weight'] for e in range(lm_config.num_experts)])
  74. state_dict = new_sd
  75. qwen_model.load_state_dict(state_dict, strict=True)
  76. qwen_model = qwen_model.to(dtype) # 转换模型权重精度
  77. qwen_model.save_pretrained(transformers_path)
  78. model_params = sum(p.numel() for p in qwen_model.parameters() if p.requires_grad)
  79. print(f'模型参数: {model_params / 1e6} 百万 = {model_params / 1e9} B (Billion)')
  80. tokenizer = AutoTokenizer.from_pretrained('../model/')
  81. tokenizer.save_pretrained(transformers_path)
  82. # ======= transformers-5.0的兼容低版本写法 =======
  83. if int(transformers.__version__.split('.')[0]) >= 5:
  84. tokenizer_config_path, config_path = os.path.join(transformers_path, "tokenizer_config.json"), os.path.join(transformers_path, "config.json")
  85. json.dump({**json.load(open(tokenizer_config_path, 'r', encoding='utf-8')), "tokenizer_class": "PreTrainedTokenizerFast", "extra_special_tokens": {}}, open(tokenizer_config_path, 'w', encoding='utf-8'), indent=2, ensure_ascii=False)
  86. config = json.load(open(config_path, 'r', encoding='utf-8'))
  87. config['rope_theta'] = lm_config.rope_theta; config['rope_scaling'] = None; del config['rope_parameters']
  88. json.dump(config, open(config_path, 'w', encoding='utf-8'), indent=2, ensure_ascii=False)
  89. print(f"模型已保存为 Transformers 格式: {transformers_path}")
  90. def convert_transformers2torch(transformers_path, torch_path):
  91. model = AutoModelForCausalLM.from_pretrained(transformers_path, trust_remote_code=True)
  92. torch.save({k: v.cpu().half() for k, v in model.state_dict().items()}, torch_path)
  93. print(f"模型已保存为 PyTorch 格式: {torch_path}")
  94. def convert_merge_base_lora(base_torch_path, lora_path, merged_torch_path):
  95. device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
  96. lm_model = MiniMindForCausalLM(lm_config).to(device)
  97. state_dict = torch.load(base_torch_path, map_location=device)
  98. lm_model.load_state_dict(state_dict, strict=False)
  99. apply_lora(lm_model)
  100. merge_lora(lm_model, lora_path, merged_torch_path)
  101. print(f"LoRA 已合并并保存为基模结构 PyTorch 格式: {merged_torch_path}")
  102. def convert_jinja_to_json(jinja_path):
  103. with open(jinja_path, 'r') as f: template = f.read()
  104. escaped = json.dumps(template)
  105. print(f'"chat_template": {escaped}')
  106. def convert_json_to_jinja(json_file_path, output_path):
  107. with open(json_file_path, 'r') as f: config = json.load(f)
  108. template = config['chat_template']
  109. with open(output_path, 'w') as f: f.write(template)
  110. print(f"模板已保存为 jinja 文件: {output_path}")
  111. if __name__ == '__main__':
  112. lm_config = MiniMindConfig(hidden_size=768, num_hidden_layers=8, max_seq_len=8192, use_moe=True)
  113. # convert torch to transformers
  114. torch_path = f"../out/full_sft_{lm_config.hidden_size}{'_moe' if lm_config.use_moe else ''}.pth"
  115. transformers_path = '../minimind-3-moe'
  116. convert_torch2transformers(torch_path, transformers_path)
  117. # # merge lora
  118. # base_torch_path = f"../out/full_sft_{lm_config.hidden_size}{'_moe' if lm_config.use_moe else ''}.pth"
  119. # lora_path = f"../out/lora_identity_{lm_config.hidden_size}.pth"
  120. # merged_torch_path = f"../out/merge_identity_{lm_config.hidden_size}{'_moe' if lm_config.use_moe else ''}.pth"
  121. # convert_merge_base_lora(base_torch_path, lora_path, merged_torch_path)
  122. # convert_transformers2torch(transformers_path, torch_path)
  123. # convert_json_to_jinja('../model/tokenizer_config.json', '../model/chat_template.jinja')
  124. # convert_jinja_to_json('../model/chat_template.jinja')