convert_model.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import torch
  2. import warnings
  3. import sys
  4. import os
  5. __package__ = "scripts"
  6. sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
  7. from transformers import AutoTokenizer, AutoModelForCausalLM
  8. from model.LMConfig import LMConfig
  9. from model.model import MiniMindLM
  10. warnings.filterwarnings('ignore', category=UserWarning)
  11. def convert_torch2transformers(torch_path, transformers_path):
  12. def export_tokenizer(transformers_path):
  13. tokenizer = AutoTokenizer.from_pretrained('../model/minimind_tokenizer')
  14. tokenizer.save_pretrained(transformers_path)
  15. LMConfig.register_for_auto_class()
  16. MiniMindLM.register_for_auto_class("AutoModelForCausalLM")
  17. lm_model = MiniMindLM(lm_config)
  18. device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
  19. state_dict = torch.load(torch_path, map_location=device)
  20. lm_model.load_state_dict(state_dict, strict=False)
  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. export_tokenizer(transformers_path)
  25. print(f"模型已保存为 Transformers 格式: {transformers_path}")
  26. def convert_transformers2torch(transformers_path, torch_path):
  27. model = AutoModelForCausalLM.from_pretrained(transformers_path, trust_remote_code=True)
  28. torch.save(model.state_dict(), torch_path)
  29. print(f"模型已保存为 PyTorch 格式: {torch_path}")
  30. # don't need to use
  31. def push_to_hf(export_model_path):
  32. def init_model():
  33. tokenizer = AutoTokenizer.from_pretrained('../model/minimind_tokenizer')
  34. model = AutoModelForCausalLM.from_pretrained(export_model_path, trust_remote_code=True)
  35. return model, tokenizer
  36. model, tokenizer = init_model()
  37. # model.push_to_hub(model_path)
  38. # tokenizer.push_to_hub(model_path, safe_serialization=False)
  39. if __name__ == '__main__':
  40. lm_config = LMConfig(dim=512, n_layers=8, max_seq_len=8192, use_moe=False)
  41. torch_path = f"../out/reason_{lm_config.dim}{'_moe' if lm_config.use_moe else ''}.pth"
  42. transformers_path = '../MiniMind2-Small-R1'
  43. # convert torch to transformers model
  44. convert_torch2transformers(torch_path, transformers_path)
  45. # # convert transformers to torch model
  46. # convert_transformers2torch(transformers_path, torch_path)