0-eval_pretrain.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. import random
  2. import time
  3. import numpy as np
  4. import torch
  5. import warnings
  6. from transformers import AutoTokenizer, AutoModelForCausalLM
  7. from model.model import Transformer
  8. from model.LMConfig import LMConfig
  9. warnings.filterwarnings('ignore')
  10. def count_parameters(model):
  11. return sum(p.numel() for p in model.parameters() if p.requires_grad)
  12. def init_model(lm_config):
  13. tokenizer = AutoTokenizer.from_pretrained('./model/minimind_tokenizer')
  14. model_from = 1 # 1从权重,2用transformers
  15. if model_from == 1:
  16. moe_path = '_moe' if lm_config.use_moe else ''
  17. ckp = f'./out/pretrain_{lm_config.dim}{moe_path}.pth'
  18. model = Transformer(lm_config)
  19. state_dict = torch.load(ckp, map_location=device)
  20. # 处理不需要的前缀
  21. unwanted_prefix = '_orig_mod.'
  22. for k, v in list(state_dict.items()):
  23. if k.startswith(unwanted_prefix):
  24. state_dict[k[len(unwanted_prefix):]] = state_dict.pop(k)
  25. for k, v in list(state_dict.items()):
  26. if 'mask' in k:
  27. del state_dict[k]
  28. # 加载到模型中
  29. model.load_state_dict(state_dict, strict=False)
  30. else:
  31. model = AutoModelForCausalLM.from_pretrained('minimind', trust_remote_code=True)
  32. model = model.to(device)
  33. print(f'模型参数: {count_parameters(model) / 1e6} 百万 = {count_parameters(model) / 1e9} B (Billion)')
  34. return model, tokenizer
  35. def setup_seed(seed):
  36. random.seed(seed) # 设置 Python 的随机种子
  37. np.random.seed(seed) # 设置 NumPy 的随机种子
  38. torch.manual_seed(seed) # 设置 PyTorch 的随机种子
  39. torch.cuda.manual_seed(seed) # 为当前 GPU 设置随机种子(如果有)
  40. torch.cuda.manual_seed_all(seed) # 为所有 GPU 设置随机种子(如果有)
  41. torch.backends.cudnn.deterministic = True # 确保每次返回的卷积算法是确定的
  42. torch.backends.cudnn.benchmark = False # 关闭 cuDNN 的自动调优,避免不确定性
  43. if __name__ == "__main__":
  44. # -----------------------------------------------------------------------------
  45. out_dir = 'out'
  46. start = ""
  47. temperature = 0.7
  48. top_k = 8
  49. setup_seed(1337)
  50. # device = 'cpu'
  51. device = 'cuda:0' if torch.cuda.is_available() else 'cpu'
  52. dtype = 'bfloat16'
  53. max_seq_len = 512
  54. lm_config = LMConfig()
  55. lm_config.max_seq_len = max_seq_len
  56. # -----------------------------------------------------------------------------
  57. model, tokenizer = init_model(lm_config)
  58. model = model.eval()
  59. # int(input('输入0自动测试,输入1问题测试:'))
  60. answer_way = 0
  61. stream = True
  62. prompt_datas = [
  63. '椭圆和圆的区别',
  64. '中国关于马克思主义基本原理',
  65. '人类大脑的主要功能是',
  66. '万有引力是',
  67. '世界上人口最多的国家是',
  68. 'DNA的全称是',
  69. '数学中π的值大约是',
  70. '世界上最高的山峰是',
  71. '太阳系中最大的行星是',
  72. '二氧化碳的化学分子式是',
  73. '地球上最大的动物是',
  74. '地球自转一圈大约需要',
  75. '杭州市的美食有',
  76. '江苏省的最好的大学',
  77. ]
  78. qa_index = 0
  79. while True:
  80. start = time.time()
  81. if answer_way == 1:
  82. # run generation
  83. prompt = input('用户:')
  84. else:
  85. if qa_index >= len(prompt_datas):
  86. break
  87. prompt = prompt_datas[qa_index]
  88. print('问题:', prompt)
  89. qa_index += 1
  90. prompt = tokenizer.bos_token + prompt
  91. x = tokenizer(prompt).data['input_ids']
  92. x = (torch.tensor(x, dtype=torch.long, device=device)[None, ...])
  93. with torch.no_grad():
  94. res_y = model.generate(x, tokenizer.eos_token_id, max_new_tokens=max_seq_len, temperature=temperature,
  95. top_k=top_k, stream=stream)
  96. print('回答:', end='')
  97. try:
  98. y = next(res_y)
  99. except StopIteration:
  100. print("No answer")
  101. continue
  102. history_idx = 0
  103. while y != None:
  104. answer = tokenizer.decode(y[0].tolist())
  105. if answer and answer[-1] == '�':
  106. try:
  107. y = next(res_y)
  108. except:
  109. break
  110. continue
  111. # print(answer)
  112. if not len(answer):
  113. try:
  114. y = next(res_y)
  115. except:
  116. break
  117. continue
  118. print(answer[history_idx:], end='', flush=True)
  119. try:
  120. y = next(res_y)
  121. except:
  122. break
  123. history_idx = len(answer)
  124. if not stream:
  125. break
  126. print('\n')
  127. end = time.time()
  128. print(end - start, 's')