export_model.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import torch
  2. import warnings
  3. from transformers import AutoTokenizer, AutoModelForCausalLM
  4. from model.LMConfig import LMConfig
  5. from model.model import Transformer
  6. warnings.filterwarnings('ignore', category=UserWarning)
  7. def count_parameters(model):
  8. return sum(p.numel() for p in model.parameters() if p.requires_grad)
  9. def export_transformers_model():
  10. LMConfig.register_for_auto_class()
  11. Transformer.register_for_auto_class("AutoModelForCausalLM")
  12. lm_config = LMConfig()
  13. lm_model = Transformer(lm_config)
  14. device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
  15. moe_path = '_moe' if lm_config.use_moe else ''
  16. ckpt_path = f'./out/full_sft_{lm_config.dim}{moe_path}.pth'
  17. state_dict = torch.load(ckpt_path, map_location=device)
  18. unwanted_prefix = '_orig_mod.'
  19. for k, v in list(state_dict.items()):
  20. if k.startswith(unwanted_prefix):
  21. state_dict[k[len(unwanted_prefix):]] = state_dict.pop(k)
  22. lm_model.load_state_dict(state_dict, strict=False)
  23. print(f'模型参数: {count_parameters(lm_model) / 1e6} 百万 = {count_parameters(lm_model) / 1e9} B (Billion)')
  24. lm_model.save_pretrained("minimind-small-T", safe_serialization=False)
  25. def export_tokenizer():
  26. tokenizer = AutoTokenizer.from_pretrained('./model/minimind_tokenizer',
  27. trust_remote_code=True, use_fast=False)
  28. tokenizer.save_pretrained("minimind-small-T")
  29. def push_to_hf():
  30. def init_model():
  31. tokenizer = AutoTokenizer.from_pretrained('./model/minimind_tokenizer',
  32. trust_remote_code=True, use_fast=False)
  33. model = AutoModelForCausalLM.from_pretrained('minimind-small', trust_remote_code=True)
  34. return model, tokenizer
  35. model, tokenizer = init_model()
  36. # 推送到huggingface
  37. model.push_to_hub("minimind-small")
  38. # tokenizer.push_to_hub("minimind-small-T", safe_serialization=False)
  39. if __name__ == '__main__':
  40. # 1
  41. export_transformers_model()
  42. # 2
  43. export_tokenizer()
  44. # # 3
  45. # push_to_hf()